gas Station
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.
Ideas:
Start at the No. 0 point and traverse the container. Use a variable remain to record the amount of oil remaining in the mailbox after each point. If the remain<0 of point I is computed, it cannot be drawn from point I, because the next point cannot be reached. Then only the starting point can be re-selected. (This starting point must not be at a certain point between the previous beginning and the I point.) It can be proved that, assuming the previous starting point is T, point I remain<0, there is a point J between T and I, then T arrives at the time of the J Remain>=0, and if the starting point is set at J Point, there is remain=0, so to point I will still have remain <0. )
So the topic is simplified, not all points are used as a starting point to traverse. If remain<0 is found at point I, then the next starting point is i+1, until it is able to cycle one lap or the starting point is greater than the capacity of a given container.
Exercises
classSolution { Public: intCancompletecircuit (vector<int> &gas, vector<int> &Cost ) { intStart =0; intremain =0; intn =gas.size (); intI=0; while(Start<n && i<start+N) {if(i<N) remain= remain+gas[i]-Cost[i]; Elseremain= remain+gas[i-n]-cost[i-N]; if(remain<0) {Start= i+1; Remain=0; } I++; } if(start>=N)return-1; returnstart; }};
View Code
[Leetcode] Gas station