There are N gas stations along a circular route, where the amount of gas at stationi is gas[i].
You have a car with an unlimited gas tank and it costscost[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
沿環形路線有N個加油站,其中氣體在車站i是量是gas[i]。你有車有無限容量的氣罐,從加油站i到下一個加油站站點i+1,要消耗cost[i]的氣體。你開始旅程時,氣罐是空的。回到起始加油站的指數,選擇一個起點開始旅游,如果你能在周圍環形旅行一次,就返回開始的加油站索引,否則返回-1。
注意: 答案保證是唯一的。
首先先要明白:如果一個數組的總和非負,那么一定可以找到一個起始位置,從他開始繞數組一圈,累加和一直都是非負的。
如果從i出發,那么gas[i]-cost[i](dif[i])一定是大於0的,程序中有判斷。如果dif[i]+dif[i+1]+……+dif[k-1]>=0,而dif[i]+dif[i+1]+……+dif[k-1]+dif[k]<0,此時需要重新設置開始點,那么需要從I+1開始嗎?dif[i]肯定大於0,所有從i
+1開始,肯定不可能到達k點,少加了一個正數。那么需要設置開始點為K+1;
public int canCompleteCircuit(int[] gas, int[] cost) {
// 記錄訪問的起始點
int start = 0;
// 加的氣和消耗的氣的總差值(從0開始)
int total = 0;
// 從start位置開始,加的氣和消耗的氣的總差值
int sum = 0;
for (int i = 0; i < gas.length; i++) {
int dif = gas[i] - cost[i];
sum += dif;
total += dif;
// 走到i站是負數,說明走不到i站,
// 也不能選取起始站到i站中的任何一戰
if (sum < 0) {
sum = 0;
// 下一站作為起始點
start = i + 1;
}
}
return total >= 0 ? start : -1;
}