标签:
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.
Greedy
引自Lexi‘s Leetcode solutions 的解答:
以上做法,其实是贪心的思想:
也就是说brute force的解是 : 一个一个来考虑, 每一个绕一圈, 但是 实际上 我们发现 i - j不可行 直接index就跳到j+1, 这样周而复始,很快就是绕一圈 就得到解了。
1 public class Solution { 2 public int canCompleteCircuit(int[] gas, int[] cost) { 3 if (gas == null || cost == null || gas.length == 0 || cost.length == 0) { 4 // Bug 0: should not return false; 5 return -1; 6 } 7 8 int total = 0; 9 int sum = 0; 10 11 int startIndex = 0; 12 13 int len = gas.length; 14 for (int i = 0; i < len; i++) { 15 int dif = gas[i] - cost[i]; 16 sum += dif; 17 18 if (sum < 0) { 19 // Means that from 0 to this gas station, none of them can be the solution. 20 startIndex = i + 1; // Begin from the next station. 21 sum = 0; // reset the sum. 22 } 23 24 total += dif; 25 } 26 27 if (total < 0) { 28 return -1; 29 } 30 31 return startIndex; 32 } 33 }
https://github.com/yuzhangcmu/LeetCode_algorithm/blob/master/greedy/CanCompleteCircuit.java
标签:
原文地址:http://www.cnblogs.com/yuzhangcmu/p/4179228.html