題目:
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.
沿環(huán)形路線有N個加油站,其中第 i 站的煤氣量為gas[ i ]。你有一輛有一個無限制油箱的汽車,從 i 站到下一站(i+1)要花費大量的汽油。你從一個加油站并且初始油箱為空開始旅程。如果你可以繞環(huán)路一次,返回啟程加油站的索引,否則返回-1。
注意:解決方案保證是唯一的。
思路:
用最后一個點作為起點,當(dāng)油量夠時則end++,當(dāng)油量不夠就start后退一個直至到0,換起點后不需計算后續(xù)點,只需要計算剛才結(jié)余即可
public class Solution {
public int canCompleteCircuit(int[] gas, int[] cost) {
int start = gas.length - 1;
int end = 0;
int sum = gas[start] - cost[start];
while(start > end){
if(sum > 0){
sum += gas[end] - cost[end];
end++;
} else {
start--;
sum += gas[start] - cost[start];
}
}
return sum >= 0 ? start : -1;
}
}