The original title link is here: https://leetcode.com/problems/gas-station/
See this post: http://pisxw.com/algorithm/Gas-Station.html
Sumcur is the remaining oil in the current oil station, and TOTALCIR is the remaining amount of oil that goes through a whole lap. If you walk from the starting station to I station, the current remaining oil volume Sumcur < 0 is not able to walk to the I station, at the same time can not walk to the beginning of the station to the middle of any one station.
Suppose K station is the start station to I station in the middle of a station, because is walked to I just stop, go to K did not stop, so go to K when sumcur actually sumcur or positive, but go to I when sumcur turned negative.
Now suppose from K station actually so sumcur is 0, go to i words is definitely a negative number, because positive sumcur go to I have been reduced to negative, let alone is 0 of sumcur it.
Totalcir is actually used to determine whether it is possible to go through a circle, if Totalcir is a positive number, that means I can walk a circle from I point, starting from I and a lap starting from 0 with oil unchanged, the amount of oil is constant, so you can use directly. return directly to Index+1.
Note: Notice that one case is that the SUMCIR, which starts at 0, is always non-negative and returns to Index+1, which is directly related to the initialization of index. Index initialized to -1,index+1 is exactly 0.
AC Java:
1 Public classSolution {2 Public intCancompletecircuit (int[] Gas,int[] cost) {3 if(Gas = =NULL|| Cost = =NULL|| Gas.length = = 0 | | Cost.length = = 0 | | Gas.length! =cost.length) {4 return-1;5 }6 intsumcur = 0;//remaining oil at the current oil station7 intTotalcir = 0;//finish the remaining amount of oil in a whole lap8 intindex =-1;9 for(inti = 0; i<gas.length; i++){Ten intdiff = gas[i]-Cost[i]; OneSumcur + =diff; ATotalcir + =diff; - if(Sumcur < 0) {//Walk to I station is a negative number, indicating that I can not go to the station, can not select the starting station to I station any one of the war -Sumcur = 0; theindex = i;//Updating index is related to the initial conditions of index - } - } - returnTotalcir >= 0? Index+1:-1; + } -}
Leetcode gas Station