leetcode-134. 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.

題意解析:

題目大概就是說有一個環形的路線,路線上有很多分佈的加油站,每個加油站的油量是```gas[i]```,然後你開一輛車,從某一個加油站出發,看看能否繞一圈,從一個加油站到下一個加油站需要的油量是‘’‘cost[i]’‘’。如果可以的話,就返回出發的那個加油站的下標```i```,不行的話就返回-1。

答案假定是唯一的。

首先按照正常思路可以想到一個暴力解決的方法,就是去循環遍歷每個結點,試着環繞一圈,代碼如下:

public class Solution {
    public int canCompleteCircuit(int[] gas, int[] cost) {
        for(int i = 0; i < gas.length; i++){
            int currentGas = gas[i];
            int j = i;
            while(currentGas >= cost[j]){
                //能夠到達下一站
                currentGas -= cost[j];
                j = (j+1) % gas.length;
                if(j == i){
                    return i;
                }
                currentGas += gas[j];
            }
        }
        return -1;
    }
}
上述代碼複雜度O(n^2),思路簡單清晰,然而,難度是Medium的題目怎麼可能就這麼解決呢?

提交代碼,超時了。很尷尬,只能想一些巧妙的方法。

這裏應該這麼想,想要完成全程其實只要滿足兩個條件即可,第一個是,所有的gas和大於cost和。第二個就是,當前油量可以到達下一站。第二個條件的實現有點抽象,我會在代碼裏解釋,並在後面給出更詳細的說明,代碼如下:

public class Solution {
    public int canCompleteCircuit(int[] gas, int[] cost) {
        int sum = 0;
        int total = 0;
        int j = 0;
        for(int i = 0; i < gas.length; i++){
            sum += gas[i] - cost[i];
            total += gas[i] - cost[i];
            if(sum < 0){
                //說明此時汽車無法到達下一站,所以之前所有的i包括當前i都不能作爲起點。起點只可能是後面的某個值
                j = i + 1;
                sum = 0;
            }
        }
        if(total >= 0){
            return j;
        }else{
            return -1;
        }
    }
}
這個算法用total來表示總油量是足夠支持到下一站的,sum則表示能不能到達下一站,可以證明:如果```gas[i] >= cost[i]```,則可以出發,並且帶有儲存油量,如果一直保持了```gas[i] >= cost[i]```這個條件,則說明儲存的油量是在不斷增加的,所以如果某一次出現```currestGas + gas[i] < cost[i]```,不僅說明不能從這一站出發,還說明了不能從之前的任一站出發。所以就先假定下一站是可以出發的。


代碼複雜度是O(n),運行時間也只有1ms,已經是最優算法了,至於前面的0ms,大概是以前的數據或者是在服務器性能極好的時候進行了提交,導致時間短到離譜。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章