您的位置:首页 > 其它

LeetCode刷题笔录Gas Station

2014-07-23 11:50 260 查看
There are N gas stations along a circular route, where the amount of gas at station i is
gas[i]
.

You have a car with an unlimited gas tank and it costs
cost[i]
of gas
to travel from station i to its next station (i+1). You begin the journey with an 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.

这题挺有意思的。但是我想了半天也只会个O(n^2)的解法。

这里有一个非常棒的解法,和最大连续子序列的题很像。

public class Solution {
public int canCompleteCircuit(int[] gas, int[] cost) {
int[] diff = new int[gas.length];
for(int i = 0; i < gas.length; i++){
diff[i] = gas[i] - cost[i];
}

int startNode = 0, sum = 0, remainGas = 0;
for(int i = 0; i < gas.length; i++){
remainGas += diff[i];
sum += diff[i];
//if sum < 0, then the start node cannot be between 0 and i
if(sum < 0){
startNode = i + 1;
sum = 0;
}
}

if(remainGas < 0)
return -1;
return startNode;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: