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.
Notice
The solution is guaranteed to be unique.
Example
Given 4 gas stations with gas[i]=[1,1,3,1], and the cost[i]=[2,2,1,1]. The starting gas station's index is 2.
思路
贪心法
和jump game有点相似。维护一个当前油箱curTank。当油箱没有油的时候,说明从起始点没有办法开到这个油站。那么我们把候选油站选为下一站,并更新curTank为0重新开始统计。
循环结束的时候,根据题意,一定有一个唯一解。如果所有油箱的总油量减去开一圈需要的油小于0,说明无解。反之,一定有一个唯一解。时间复杂度O(n)。空间复杂度O(1)。
本题解法正确的具体证明在这里
https://leetcodenotes.wordpress.com/2013/11/21/leetcode-gas-station-转圈的加油站看能不能走一圈/
http://bangbingsyb.blogspot.com/2014/11/leetcode-gas-station.html
http://bookshadow.com/weblog/2015/08/06/leetcode-gas-station/
Code
public class Solution { /** * @param gas: an array of integers * @param cost: an array of integers * @return: an integer */ public int canCompleteCircuit(int[] gas, int[] cost) { // write your code here int totalGas = 0; int curLeftOver = 0; int candidateIndex = 0; for (int i = 0; i < gas.length; i++) { totalGas += gas[i] - cost[i]; curLeftOver += gas[i] - cost[i]; if (curLeftOver < 0) { candidateIndex = i + 1; curLeftOver = 0; } } return totalGas < 0 ? -1 : candidateIndex; } }