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.
class Solution {
public:
int canCompleteCircuit(vector<int> &gas, vector<int> &cost) {
int i, j, n = gas.size();
/*
* If start from i, stop before station x -> no station k from i + 1 to x - 1 can reach x.
* Bcoz if so, i can reach k and k can reach x, then i reaches x. Contradiction.
* Thus i can jump directly to x instead of i + 1, bringing complexity from O(n^2) to O(n).
*/
// start from station i
for (i = 0; i < n; i += j) {
int gas_left = 0;
// forward j stations
for (j = 1; j <= n; j++) {
int k = (i + j - 1) % n;
gas_left += gas[k] - cost[k];
if (gas_left < 0)
break;
}
if (j > n)
return i;
}
return -1;
}
};
这道题有个小hint,那就是如果从一个点i开始不能到达点j,那么在[i+1,j-1]之间也不会存在一个能到点j的点。
因为如果点i能到点k,点k能到点j,那么点i一定能到点j,所以我们就可以一次性从点i跳到点j进行下一次的选点重新开始计算。
如果每次失败时候从下一个点开始搜索那么需要o(f(x))=o(n*(n-1)/2)=o(n^2),若采用上面的小技巧,如果跳过了k次,那么只需要o(kn) = o(n)时间复杂度。