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
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.
这题挺有意思的。但是我想了半天也只会个O(n^2)的解法。
在这里有一个非常棒的解法,和最大连续子序列的题很像。
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; } }
相关文章推荐
- [Leetcode] gas station 气站
- LeetCode gas-station
- leetcode — gas-station
- Leetcode: Gas Station
- LeetCode-134. Gas Station(JAVA)加气站问题
- LeetCode "Gas Station" - TO BE REVISED
- Leetcode Gas Station
- [leetcode] Gas Station
- leetcode之Gas Station
- [LeetCode] Gas Station
- Leetcode | Gas Station
- [leetcode] Gas Station
- Leetcode:Gas Station
- leetCode---Gas Station
- leetcode---Gas Station---动规
- Leetcode: Gas Station
- Leetcode:Gas Station
- leetcode - Gas Station
- 【leetCode百题成就】Gas Station解题报告
- leetcode gas-station【最大序列变形】