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.
/*我们从0开始以其为起点实验,累加 remain += gas[i] - cost[i],一旦在 i 处遇到remain<0,那么就说明当前选择的起点beg不行, 需要重新选择,此时我们不应该回去使用 beg+1 作为新起点,因为在beg处,一定有 gas>=cost, 说明 beg+1 到 i 处的总gas一定小于总的cost,选择其中任何一个作为起点还是不行的,所以应该跳过这些点, 以 i+1 作为新起点,遍历到 size-1 处就可以结束了,如果找到了可能的起点,我们还要进行验证,走一遍(total), 如果没问题那么说明可以。*/ class Solution { public: int canCompleteCircuit(vector<int>& gas, vector<int>& cost) { if(gas.empty()) return -1; int len=gas.size(); int remain=0; int sum=0; int begin=0; for(int i=0;i<=len-1;i++) { remain+=gas[i]-cost[i]; sum+=gas[i]-cost[i]; if(remain<0) { begin=i+1; remain=0; } } return sum>=0?begin:-1; } };