您的位置:首页 > 编程语言 > Java开发

Java for LeetCode 134 Gas Station

2015-06-02 10:44 405 查看
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.

解题思路:

由于答案唯一,所以,只能按照一个方向走(不需要考虑从i+1→i的情况)

考虑到从i出发,到达i+j之后无法前进,那么从i+i出发,最多也只能到达i+j,所以下次循环可以从i+j+1开始,JAVA实现如下:

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