1、题目
在一条环路上有 N 个加油站,其中第 i 个加油站有汽油 gas[i] 升。
你有一辆油箱容量无限的的汽车,从第 i 个加油站开往第 i+1 个加油站需要消耗汽油 cost[i] 升。你从其中的一个加油站出发,开始时油箱为空。
如果你可以绕环路行驶一周,则返回出发时加油站的编号,否则返回 -1。
说明:
如果题目有解,该答案即为唯一答案。
输入数组均为非空数组,且长度相同。
输入数组中的元素均为非负数。
链接:https://leetcode-cn.com/problems/gas-station
2、思路分析
1)一次遍历
从当前的i 开始,计算当前花费和拥有的大小,花费多则直接break;
注意:如何从i 的值开始访问,又回到i 这个位置,注意i 和cnt 的变化。
class Solution {
public:
int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
int n = gas.size();
int i = 0;
while(i < n){
int sumOfGas = 0, sumOfCost = 0;
int cnt = 0;
while(cnt < n){ // cnt表示访问次数,在i的基础上加,这样就可以全部访问所有的数字
int j = (cnt + i) % n;
sumOfCost += cost[j];
sumOfGas += gas[j];
if(sumOfCost > sumOfGas){ // 花费比拥有多直接break
break;
}
++cnt;
}
if(cnt == n){ // 如果此时相等,说明已经访问了n次
return i;
}
else {
i = i + cnt + 1; // 反之i+cnt前面都不能满足条件
}
}
return -1;
}
};