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.
之前自己想的解決方案是O(n^2)的,類似於DFS的方案,百度之,發現一個O(n)的解決方案,地址(http://blog.csdn.net/jellyyin/article/details/12245429)。
解決思路簡要如下:
1. 首先假設gas[i]-cost[i] 的差的數組爲 diff[i]
2. 全局有解的重要條件是 diff 數組的和大於等於0
3. 從零往後遍歷diff數組,記錄兩個值,一個全局的和,一個局部的和,兩個和的算法是一樣的,但用處不一樣, 全局的和用來最後判斷是否有解,局部的和稍微麻煩一點,我們用從0開始得局部和舉例子,假如說在 k 碰到第一個小於零的局部和,那麼起點不可能在 0~k 之間的任意一點。這時假設起點爲 (k+1)%diff.length, 然後清零局部和。
代碼如下:
public class Solution { public int canCompleteCircuit(int[] gas, int[] cost) { int length = gas.length; int[] diff = new int[length]; for(int i=0;i<length;i++){ diff[i] = gas[i] - cost[i]; } int start = 0; int sum = 0; int part_sum =0; for(int i=0;i<length;i++){ sum += diff[i]; part_sum += diff[i]; if(part_sum<0){ start = (i+1)%length; part_sum = 0; } } return sum>=0?start:-1; } }