LeetCode——Gas Station

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.

贪心or动态规划?

从gas[0]开始走,遇到油不够的情况,开始station就后退一步,利用以前算的结果可以只算出第一步的油量。直到最后,算出circle的连接点是否满足。

public class Solution {
    public int canCompleteCircuit(int[] gas, int[] cost) {
        
        int n = gas.length;
        
        int start = 0, end = 0, have = 0, cur = 0;
        
        for(int i=0; i<n-1; i++) {
            have += gas[cur] - cost[cur];
            if(have >= 0) {
                end ++;
                cur = end;
            }
            else {
                start --;
                if(start < 0) {
                    start = n - 1;
                }
                cur = start;
            }
        }
        
        have += gas[cur] - cost[cur];
        
        return have>=0?start:-1;
    }
}

 

posted @ 2015-10-15 10:33  Pickle  阅读(190)  评论(0)    收藏  举报