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.

加油站问题,每个加油站可以加的油给出来,从当前当下一个加油站会消耗的汽油量给出来了,求从哪个站点出发可以循环加油站一圈。

一开始是用一个二重循环的,这样复杂度为N^2,一直TLE,代码如下:

 class Solution {
public:
int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
for(int i = ; i < gas.size(); ++i){
int j = i;
int curGas = gas[j];
while(curGas >= cost[j]){
curGas -= cost[j];
j = (j+)%gas.size();
curGas += gas[j];
if(j == i)
return i;
}
}
return -;
}
};

那只能使用其他方法了,可以看出维护一个部分差的和,如果前面的部分差的和一旦小于0的话,那么可以肯定的是应该在当前节点的下一处开始,然后在维护一个整体的和,当检查部分和可以完成时,查看整体差值是否小于0就可以了,代码如下所示:

 class Solution {
public:
int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
int totalLeft = ;
int sum = ;
int j = -;
for(int i = ; i < gas.size(); ++i){
totalLeft += gas[i] - cost[i];
sum += gas[i] - cost[i];
if(sum < ){
j = i;
sum = ;
}
}
if(totalLeft < )
return -;
return j + ;
}
};
05-11 12:54