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.
遇到一个无法到达的站则把起点向前推,如果推了一圈则说明无法到达
class Solution { public: int canCompleteCircuit(vector<int> &gas, vector<int> &cost) { // Note: The Solution object is instantiated only once and is reused by each test case. int bal=0; int start=0; for(int i=0;i<gas.size();i++){ int pos=start+i; if(pos>=gas.size())pos-=gas.size(); bal+=gas[pos]; bal-=cost[pos]; while(bal<0){ start--; if(start<0)start=gas.size()-1; i++; if(i==cost.size())return -1; bal+=gas[start]; bal-=cost[start]; } } return start; } };