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.
Public classSolution {/*we start from 0 to its starting point experiment, add Restgas + = Gas[i]-cost[i], once I encounter restgas<0, then the current selection of the starting point beg No, need to re-select, at this time we should not go back to use beg+1 as a new Point, because in the beg place, must have gas>=cost, explain beg+1 to I where the total gas must be less than the total cost, choose any one of them as a starting point or not, so should skip these points, to i+1 as a new starting point, traverse to size-1 can end , if we find a possible starting point, we have to verify, go through (total), if there is no problem then the explanation can be. *//*in fact, the essence is: the beginning of the path is divided into two paragraphs, the total margin of the former is negative, that is, oil is not enough, to have a solution, then the oil content should be positive, at this time may have a solution, we have to do is to find this point as a starting point, and then verify it; Then obviously you can directly select the front point as the starting point, and if the whole paragraph is negative, then no solution. */ Public intCancompletecircuit (int[] Gas,int[] cost) { intI=0; intLeft=0; intBeg=0; intTotal=0; while(i<gas.length) { Left+=gas[i]-Cost[i]; Total+=gas[i]-cost[i];//total in order to verify that the entire array is gas>cost if(left<0) {Beg=i+1; Left=0; } I++; } if(total>=0)returnBeg; Else return-1; }}
[Leedcode 134] Gas station