[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.

https://oj.leetcode.com/problems/gas-station/

 

思路:O(n^2)的算法太简单肯定不是最优,可以有O(n)的算法。

设置两个变量,total和sum,total一直累积gas和cost的差值,如果最后>0表示肯定有可行方案;sum也累积计算gas和cost的差值,但是一旦小于0,要清空,从下一个点开始作为起点继续尝试。

public class Solution {
    public int canCompleteCircuit(int[] gas, int[] cost) {
        int len = gas.length;
        int idx = -1;
        int sum = 0;
        int total = 0;

        for (int i = 0; i < len; i++) {
            sum += gas[i] - cost[i];
            total += gas[i] - cost[i];
            if (sum < 0) {
                idx = i;
                sum = 0;
            }
        }

        if (total < 0)
            return -1;
        else
            return idx + 1;

    }

    public static void main(String[] args) {
        int[] gas = { 5, 5, 5, 2, 2 };
        int[] cost = { 0, 8, 2, 5, 2 };
        System.out.println(new Solution().canCompleteCircuit(gas, cost));
    }
}

 

第二遍记录:

public class Solution {
    public int canCompleteCircuit(int[] gas, int[] cost) {
        int n = gas.length;
        int idx= -1;
        int total=0;
        int tmpSum=0;
        
        for(int i=0;i<n;i++){
            total += gas[i]-cost[i];
            tmpSum += gas[i]-cost[i];
            if(tmpSum<0){
                tmpSum=0;
                idx=i;
            }
        }
        if(total<0)
            return -1;
        
        return idx+1;
        
        
    }
}

 

第三遍记录:

  注意如果idx的初始值,加入sum一直>=0的话,会返回初始值。

  有点类似maximum subarray。

public class Solution {
    public int canCompleteCircuit(int[] gas, int[] cost) {
        int n =gas.length;
        int total=0;
        int sum =0;
        int idx=0;
        
        for(int i=0;i<n;i++){
           total +=gas[i]-cost[i]; 
           sum +=gas[i]-cost[i];
           if(sum<0){
               sum=0;
               idx=i+1;
           }
        }
        
        if(total<0)
            return -1;
        else
            return idx;
        
    }

}

 

 

参考:

http://blog.csdn.net/sunnyyoona/article/details/18742287

http://blog.csdn.net/kenden23/article/details/14106137

posted @ 2014-07-07 00:12  jdflyfly  阅读(157)  评论(0编辑  收藏  举报