There was N gas stations along a circular route, where the amount of gas at Station I was gas[i]
.
You had a car with an unlimited gas tank and it costs of gas to travel from station cost[i]
I to its next station (i+ 1). You begin the journey with a 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) { int Length=gas.size (); Vector<int> Tmpgas (length,0); for (int i=0;i<length;++i) { tmpgas[i]=gas[i]-cost[i];//a new array of difference, representing the complement or consumption } int startindex=0 ;//initial starting point int sum=tmpgas[startindex]; int i=0; while (true) { i++; if (i>=length) { i=i-length; } if (sum<0) { startindex=i;//one of the following nodes as the starting point if (startindex==0) return-1;//back to the initial starting point, the loop begins to appear Sum=tmpgas[startindex]; } else { sum+=tmpgas[i];
<span style= "White-space:pre" ></span> //has reached the finish line to determine if the whole process can be successfully completed if (startindex==0 && i== Length-1) {//If the starting point is 0, the current node is also the last nodes if (sum<0) return-1; else return startIndex; } if (i==startindex-1) {//If the current node is the last node of the loop if (sum>=0) return startIndex; else return-1;}}}} ;
Leetcode (WU): Gas station