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.
Subscribe to see which companies asked this question
class Solution {
public:
int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
const int length = gas.size();
int sum = 0;
int total = 0;
int j = -1;
for(int i = 0; i < length; ++i)
{
sum += gas[i] - cost[i];
total += gas[i] - cost[i];
if(sum < 0)
{
j = i ;
sum = 0;
}
}
if(total < 0)
{
return -1;
}
else
{
return j + 1;
}
}
};
题目详解:
1.total值是用来记录整个能量圈的正负,如果整个圈都是负值,那么怎么跑都不可能跑完
2.sum值是用来记录里面局部的能量正负,局部可能会gas特别多可以用于下一段,也可能缺失,直接跳到下一个点进行。
总之,只要能量圈的总值是正的,那么就肯定能跑完有解。