您的位置:首页 > 其它

Gas Station

2016-06-21 17:37 316 查看
一道智力题,抛去n方的解法,对于下面的做法,真的得能找到规律。

当中的题眼是The solution is guaranteed to be unique.,于是

i:    5,10,4,20,7

c: 10,11,2,10,9

就不满足,因为从4,或20都可以开始。既然unique,即如果前面所有的gas - cost加起来小于零,那么前面所有的点都不能作为出发点。

参考:点击打开链接点击打开链接

public class Solution {
public int canCompleteCircuit(int[] gas, int[] cost) {
if (gas == null || gas.length == 0 || cost == null || cost.length == 0 || gas.length != cost.length) {
return -1;
}
int sum = 0, total = 0, index = 0;
for (int i = 0; i < gas.length; i++) {
sum = sum + gas[i] - cost[i];
total = total + gas[i] - cost[i];
if (sum < 0) {
sum = 0;
index = i + 1;
}
}
if (total < 0) {
return -1;
} else {
return index;
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: