There areNGas stations along a circular route, where the amount of gas at StationIIsgas[i]
.
You have a car with an unlimited gas tank and it costscost[i]
Of gas to travel from StationITo 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) {int num = gas. size (); int remain = 0; // int start = 0; For (INT I = 0; I <num ;) {If (cost [I]> gas [I]) {I ++; continue;} else {start = I; // mark start station remain = gas [I]-cost [I]; I ++; while (I <num & gas [I] + remain> = cost [I]) {remain = (gas [I] + remain-cost [I]); I ++;} if (I = num) {I = 0;} else {start = I + 1; I = start; continue ;} while (gas [I] + remain> = cost [I] & I <start) {remain = (gas [I] + remain-cost [I]); I ++;} if (I = Start) {return start;} else {return-1 ;}}// end for return-1 ;}};