Question
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.
Note:
The solution is guaranteed to be unique.
本题难度Medium。
【题意】
如果有解,解是唯一的;如果无解,返回-1。
【复杂度】
时间 O(N) 空间 O(1)
【思路】
用sum
表示当前 station i1 作为起点时到达station i2 的油量;用j
标记起点station的前一个station;用total
判断整个数组是否有解。有解就通过j
来得到起点,没有解就返回-1
。
【附】
如果本题有解,而某个点上sum<0
,就说明其中必然有且只有1个station的gas“特别地多”,但是目前还没遍历到该station。能这样判断的原因就在于如果有解就是唯一的解。
【代码】
public class Solution {
public int canCompleteCircuit(int[] gas, int[] cost) {
//require
int size=gas.length;
int j=-1,sum=0,total=0;
//invariant
for(int i=0;i<size;i++){
sum+=gas[i]-cost[i];
total+=gas[i]-cost[i];
//sum<0,说明从i1到i2都不可以作为起点,因此选下一个为起点
if(sum<0){
sum=0;
j=i;
}
}
//ensure
return total<0?-1:j+1;
}
}