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:
left 判断当前的站是否可以到达;sum 则判断整个数组是否有解,有就返回通过 left得到的下标,没有则返回 -1
class Solution {
public:
int canCompleteCircuit(vector<int> &gas, vector<int> &cost) {
int sum = 0, j = -1;
for( int i = 0, left = 0; i < gas.size(); ++i){
left += gas[i] - cost[i];
sum += gas[i] - cost[i];
if( left < 0){
j = i;
left = 0;
}
}
return sum >= 0 ? j + 1 : -1;//这里注意大于等于0就可以,等于0说明刚好
}
};