加油站
题目
在一条环路上有 N 个加油站,其中第 i 个加油站有汽油 gas[i] 升。
你有一辆油箱容量无限的的汽车,从第 i 个加油站开往第 i+1 个加油站需要消耗汽油 cost[i] 升。你从其中的一个加油站出发,开始时油箱为空。
如果你可以绕环路行驶一周,则返回出发时加油站的编号,否则返回 -1。
说明:
- 如果题目有解,该答案即为唯一答案。
- 输入数组均为非空数组,且长度相同。
- 输入数组中的元素均为非负数。

具体思路
- 设置
count计算是否有解,count < 0时无解; - 如果存在解,那么一定在某个位置;
- 从头开始遍历,能使得
cur变为负数的位置,一定不是解,下一个存在解的位置在之后,设置res = i + 1; - 循环结束时,得到
res;
- 从头开始遍历,能使得
关键点:
- 解是唯一的,当前计算为负数—> 一定不是解;
- 当前为正,且total为正 —> 一定是解;
具体代码
class Solution {
public:
int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
int cur = 0;
int res = 0;
int count = 0;
for (int i = 0; i < gas.size(); i++) {
// count确定有没有解
count += gas[i] - cost[i];
cur += gas[i] - cost[i];
if (cur < 0) {
cur = 0;
// cur
// 确定如果有解,那么解的位置,至少存在的解是在之后找到,因为从0开始
res = i + 1;
}
}
return count < 0 ? -1 : res;
}
};
class Solution {
public int canCompleteCircuit(int[] gas, int[] cost) {
int total = 0, cur = 0, start = 0;
for (int i = 0; i < gas.length; i++) {
int diff = gas[i] - cost[i];
total += diff;
cur += diff;
if (cur < 0) {
start = i + 1;
cur = 0;
}
}
return total < 0 ? -1 : start;
}
}
评论(0)
暂无评论