accepted:39396 Total submissions:153479
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 cost[i] of the gas-to-travel from station 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.
Problem Solving Ideas:
Because the answer is unique, you can only go in one direction (no need to consider the situation from I+1→i)
Considering the departure from I, after reaching the i+j can not go forward, then from the I+i, the maximum can only reach i+j, so the next cycle can start from i+j+1, Java implementation is as follows:
public int cancompletecircuit (int[] gas, int[] cost) {for (int i = 0; i < gas.length; i++) {int sum = gas[i]-cost[i]; int index = i, count = 0;while (sum >= 0) {if (++count = = gas.length) return index;int j = ++i% gas.length;sum + = Gas[j ]-cost[j];}} return-1;}
Java for Leetcode 134