原题:
解决方法:
代码:
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 costs cost[i]
of gas to travel from stationi 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.
解决方法:
用total来保存剩余气量,smallest表示从前到后最小的剩余气量,start指向剩余气量的下一个位置。
- 最终如果剩余气量小于0,则无法达到目标。否则从最小剩余气量的下一个位置可以到达终点。
代码:
int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
int total = 0, start = 0, smallest = INT_MAX, n = gas.size();
for(int i = 0; i < n;i++){
total += gas[i] - cost[i];
if (total < smallest){
smallest = total;
start = i + 1;
}
}
return total >= 0 ? start % n : -1;
}