Problem
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.
Solution
Key to the solution is a conclusion:
If sum of gas >= sum of costs, then there must exists one or more solution.
If sum of Gas < sum of costs, then there is no solution.
So we can use the method of exclusion here.
We need also note here is if a can not reach C in a the sequence of a-->b-->c and then B can does not make it either.
1 Public classSolution {2 Public intCancompletecircuit (int[] Gas,int[] cost) {3 if(Gas = =NULL|| Cost = =NULL)4 return-1;5 if(Gas.length! =cost.length)6 return-1;7 intStart = 0;8 intsumremaining = 0;9 inttotalremaining = 0;Ten for(inti = 0; i < gas.length; i++) { One intTMP = Gas[i]-Cost[i]; A if(sumremaining >= 0) { -Sumremaining + =tmp; -}Else { theStart =i; -Sumremaining =tmp; - } -Totalremaining + =tmp; + } - if(Totalremaining < 0) + return-1; A returnstart; at } -}
Gas station Solution