题目:在一条环路上有 N 个加油站,其中第 i 个加油站有汽油 gas[i] 升。
你有一辆油箱容量无限的的汽车,从第 i 个加油站开往第 i+1 个加油站需要消耗汽油 cost[i] 升。你从其中的一个加油站出发,开始时油箱为空。
如果你可以绕环路行驶一周,则返回出发时加油站的编号,否则返回 -1。
说明:
示例:
方法一:双循环:
class Solution {
public int canCompleteCircuit(int[] gas, int[] cost) {
int start=-1,n=gas.length,g=0,i=0,j,k;
if(n==1)return gas[0]>=cost[0]?0:-1;
while(i<n) {
if(cost[i]<gas[i]) {
start=i;
j=0;g=0;
k=start;
while(j<=n) {
g=(j!=n)?g+gas[k]-cost[k]:g+gas[i];
if(g<0)break;
k=(k+1)<n?(++k):0;
j++;
}
if(j>n)return start;
}
i++;
}
if(i==n)return -1;
return start;
}
}
方法二:单循环
class Solution {
public int canCompleteCircuit(int[] gas, int[] cost) {
int n = gas.length;
int total_tank = 0;
int curr_tank = 0;
int starting_station = 0;
for (int i = 0; i < n; ++i) {
total_tank += gas[i] - cost[i];
curr_tank += gas[i] - cost[i];
// If one couldn't get here,
if (curr_tank < 0) {
// Pick up the next station as the starting one.
starting_station = i + 1;
// Start with an empty tank.
curr_tank = 0;
}
}
return total_tank >= 0 ? starting_station : -1;
}
}