1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| class Solution { public int canCompleteCircuit(int[] gas, int[] cost) { for (int i = 0; i < gas.length; i++) { if (winnable(gas, cost, i)) { return i; } } return -1; }
private boolean winnable(int[] gas, int[] cost, int startPos) { int index = startPos; int gasLeft = 0; do { gasLeft += gas[index]; if (gasLeft >= cost[index]) { gasLeft -= cost[index]; index++; if (index >= gas.length) { index -= gas.length; } } else { return false; } } while (index != startPos); return true; } }
|