There are N gas stations along a circular route, where the amount of gas at station i is gas[i].
You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from station i to its next station (i+1). You begin the journey with an empty tank at one of the gas stations.
Return the starting gas station’s index if you can travel around the circuit once, otherwise return -1.
题意:有N个汽油站围成环,gas[i]代表每个站的汽油量,cost[i]代表开车从第i个站到下一个站(i+1)消耗的汽油量。假设你从某一个汽油站出发,此时你的车汽油缸是空的(缸容量无限),求出你可以绕这个环一圈的汽油站索引,如果没有就返回-1。
思路:假如一辆车可以绕环一圈,必有:i:0->n-1,gas[i] - cost[i]的累和>=0。所以累和小于0就说明不能绕环一圈,则返回-1;假如累和大于等于0,此时我们需要求索引,那么怎么求索引呢?
假如我们能绕环一圈,说明存在以下两种情况的一种:
- 每一站的gas[i]-cost[i]>=0
- 有些站gas[i]-cost[i]<0,有些>=0
对于第一种情况,任意i都能作为索引返回。
第二种情况:假设在第i个站有gas[i]-cost[i]<0,此时我们选择i作为起点的话,无法到达下一站,因为汽油不够。因此,无论如何,我们必须选择第j个站,且第j个站最起码需要满足条件:
- j
public class Solution {
public int canCompleteCircuit(int[] gas, int[] cost) {
int sum = 0;
int total = 0;
int start = -1;
for(int i = 0; i < gas.length; i++){
sum += gas[i] - cost[i];
total += gas[i] - cost[i];
if(sum < 0){
start = i;
sum = 0;
}
}
if(total < 0){
return -1;
}else{
return start + 1;
}
}
}