[LeetCode] Gas Station
2013-11-03 15:44
459 查看
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)。
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)。
public int canCompleteCircuit(int[] gas, int[] cost) { int length = gas.length; int start; int k = 0; // start testing from the first station while (true) { int sum = 0; start = k % length; // save the starting point do { sum += gas[k % length] - cost[k % length]; k++; } while (sum >= 0 && k < start + length); // complete a cycle if (k == start + length && sum >= 0) { return k - length; } // test from the end that has not been reached else { if (k >= length) return -1; } } }
相关文章推荐
- leetcode Two Sum
- leetcode Median of Two Sorted Arrays
- leetcode Longest Substring Without Repeating Characters
- leetcode Add Two Numbers
- leetcode Longest Palindromic Substring
- [LeetCode] Populating Next Right Pointers in Each Node
- [LeetCode] Populating Next Right Pointers in Each Node II
- [LeetCode] Distinct Subsequences
- [LeetCode] Flatten Binary Tree to Linked List
- [LeetCode] Path Sum
- [LeetCode] Path Sum II
- [LeetCode] Minimum Depth of Binary Tree - BFS
- [LeetCode] Minimum Depth of Binary Tree - DFS
- [LeetCode] Balanced Binary Tree
- [LeetCode] Convert Sorted List to Binary Search Tree
- [LeetCode] Convert Sorted Array to Binary Search Tree
- [LeetCode] Binary Tree Level Order Traversal II
- [LeetCode] Construct Binary Tree from Inorder and Postorder Traversal
- [LeetCode] Construct Binary Tree from Preorder and Inorder Traversal
- [LeetCode] Maximum Depth of Binary Tree