您的位置:首页 > 其它

Gas Station

2014-01-10 20:54 134 查看
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.

这道题上来一看就是DP,但是自己写了半天发现写不下去。只能暴力。

public class Solution {
public int canCompleteCircuit(int[] gas, int[] cost) {
int remain = 0;
int n = gas.length;
for (int i = 0; i < n; i++) {
remain = 0;
for (int j = i; j < n + i; j++) {
if (j < n) {
remain += gas[j] - cost[j];

}else{
int temp = j - n;
remain += gas[temp] - cost[temp];
}
if (remain < 0) {
break;
}
}
if (remain >= 0) {
return i;
}
}
return -1;
}
}


刚在网上看到其他的方法,挺好的。

public class Solution {
public int canCompleteCircuit(int[] gas, int[] cost) {
// Note: The Solution object is instantiated only once and is reused by each test case.
int N = gas.length, startIndex = -1;
int sum = 0, total = 0;
for(int i = 0; i < N; i++){
sum += (gas[i] - cost[i]);
total += (gas[i] - cost[i]);
if(sum < 0){
startIndex = i;
sum = 0;
}
}
return total >= 0 ? startIndex + 1 : -1;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: