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;
}
}


posted @ 2014-12-28 11:57  江南第一少  阅读(120)  评论(0)    收藏  举报