class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param grass int整型vector
* @param cost int整型vector
* @return int整型
*/
int can_complete_circuit(vector<int>& grass, vector<int>& cost) {
// write code here
int n = grass.size();
int sum1 = 0, sum2 = 0;
for (int i = 0; i < n; ++i) {
sum1 += grass[i];
sum2 += cost[i];
}
if (sum1 - sum2 < 0)
return -1;
int ans = 0, cnt = 0;
for (int i = 0; i < n; ++i) {
ans += grass[i] - cost[i];
if (ans < 0) {
cnt = i + 1;
ans = 0;
}
}
return cnt + 1;
}
};
一、题目考察的知识点
贪心
二、题目解答方法的文字分析
首先要明确如果草料的总和比消耗要少,那肯定是不能走的,所以计算一下两者之差,看看是否小于0
排除上述的可能之后就继续遍历,如果当前这一步的前缀和小于0,那么就是不满足要求,就继续遍历下一个
三、本题解析所用的编程语言
c++

京公网安备 11010502036488号