Gas Station
三年前找工作时应该做过这题,现在完全不记得了。
public class Solution {
public int canCompleteCircuit(int[] gas, int[] cost) {
if(gas == null || cost == null || gas.length == 0 || cost.length == 0 || gas.length != cost.length) {return -1;
}
int total = 0, sum = 0, index = 0;
for(int i = 0; i < gas.length; i++) {
sum += gas[i] - cost[i];
total += gas[i] - cost[i];
if(sum < 0) {
index = i + 1;
sum = 0;
}
}
return total < 0 ? -1 : index;
}
}

浙公网安备 33010602011771号