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.
思路1:遍历,试验每一个作为起点,双层循环O(N^2),超时了;
class Solution { public: int canCompleteCircuit(vector<int> &gas, vector<int> &cost) { int restGas, num; for(int i=0; i<gas.size(); ++i){ if(gas[i]>=cost[i]){ restGas = 0; num=0; for(int j=i; num<gas.size() && (restGas+gas[j])>=cost[j]; ){ restGas = restGas+gas[j]-cost[j]; num++; j = (j+1)%gas.size(); } if(num==gas.size()) return i; else continue; } } return -1; } };代码超时了。。
思路2:因为题目说了如果有解那么仅有一种,就是说只有一个可能的起点是正确的,我们从0开始以其为起点实验,累加 restGas += gas[i] - cost[i],一旦在 i 处遇到restGas<0,那么就说明当前选择的起点beg不行,需要重新选择,此时我们不应该回去使用 beg+1 作为新起点,因为在beg处,一定有 gas>=cost,说明 beg+1 到 i 处的总gas一定小于总的cost,选择其中任何一个作为起点还是不行的,所以应该跳过这些点,以 i+1 作为新起点,遍历到 size-1 处就可以结束了,如果找到了可能的起点,我们还要进行验证,走一遍,如果没问题那么说明可以。
其实本质就是:这个起点将路径分为前后两段,前段总的余量为负,即油不够用,要想有解,那么后段油量应该为正,此时才可能有解,我们要做的就是找到这个分割点作为起点,然后再验证一下;反之,如果前段就为正了,那么显然可以直接选择前面的点为起点;如果整段加起来都是负的,那么无解。
class Solution { public: int canCompleteCircuit(vector<int> &gas, vector<int> &cost) { int restGas=0; int beg=0; for(int i=0; i<gas.size(); ++i){ restGas += gas[i]-cost[i]; if(restGas<0){ restGas=0; beg = i+1; //找起点时的跳步 } } if(beg>=gas.size()) return -1; int j=beg, num=0; restGas = 0; while(num<gas.size()){ restGas += gas[j]-cost[j]; if(restGas<0) return -1; num++; j = (j+1)%gas.size(); } return beg; } };