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.
首先gas和cost相加,如果gas总量小于cost总量不计算,直接返回-1;
使用left纪录余量,i纪录开始的值,j纪录当前走到哪里了,如果到j走不下去了的话,直接从j+1开始。因为从i开始意味着gas[i]>=left[i],i缺少这个余量从i+1开始也只能到j,依次类推,既然能走到j ,从i到i+2的余量肯定大于等于0,放弃这部分从i+3开始肯定也只能最多到j。。。从而可以从j+1开始。
如果j最后等于i了,说明遍历了一圈,返回i
56ms AC
class Solution {
public:
int canCompleteCircuit(vector<int> &gas, vector<int> &cost) {
int sumgas=0,sumcost=0;
for(auto i:gas) sumgas+=i;
for(auto i:cost) sumcost+=i;
if(sumgas<sumcost) return -1;
int left=0,i=0,j=0;
while(i!=gas.size()){
if(left+gas[j]-cost[j]<0){
i=j+1;
j=i;
}
else{
left+=gas[j]-cost[j];
j++;
j%=gas.size();
if(j==i) return i;
}
}
}
};