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.
https://leetcode.com/discuss/16087/space-running-time-solution-anybody-have-posted-this-solution
https://leetcode.com/discuss/4159/share-some-of-my-ideas
这道题的基本上是建立于一个假设之上的:
如果gas[i]的和 大于等于 cost[i]的和,那么一定存在一条路径使得从第i个加油站出发,能够走一圈。
方法一:
class Solution {
public:
int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
int start = gas.size() - 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;
}
};
方法二:
class Solution {
public:
int canCompleteCircuit(vector<int> &gas, vector<int> &cost) {
int start(0), total(0), tank(0);
//if car fails at 'start', record the next station
for (int i = 0; i < gas.size(); i++) {
if ((tank = tank + gas[i] - cost[i]) < 0) {
start = i + 1;
total += tank;
tank = 0;
}
}
return (total + tank < 0) ? -1 : start;
}
};