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
You have a car with an unlimited gas tank and it costs
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,但是自己写了半天发现写不下去。只能暴力。
刚在网上看到其他的方法,挺好的。
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; } }
相关文章推荐
- Gas Station
- Gas Station
- Gas Station
- Gas Station
- LeetCode:Gas Station
- PAT 1072. Gas Station
- leetcode Gas Station
- Gas Station
- 134. Gas Station
- Gas Station
- Gas Station
- Gas Station
- Gas Station
- [LeetCode]---Gas Station
- LeetCode _ Gas Station
- Gas Station
- Gas Station
- LeetCode(134) Gas Station
- LeetCodeP134 Gas Station
- [leetcode]Gas Station