[LeetCode] Gas Station

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.

解題思路:

這套題的題意爲,有N個汽油站排成一個環。gas[i]表示第i個汽油站的汽油量,cost[i]表示第i個汽油站到第i+1個汽油站所需要的汽油。假設汽車油箱無限大。那麼求出能夠讓汽車環行一週的一個起始汽油站序號。若不存在,返回-1。

解法1:

兩次循環,分別測試每個站點,看是否能夠環行一週即可。時間複雜度爲O(n^2)。大數據產生超時錯誤。

class Solution {
public:
    int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
        int len = gas.size();
        if(len!=cost.size()){
            return -1;
        }
        for(int i=0; i<len; i++){
            int left = gas[i] - cost[i];
            int j = (i+1)%len;
            while(j!=i && left >=0){
                left += gas[j] - cost[j];
                j = (j+1)%len;
            }
            if(left>=0){
                return i;
            }
        }
        return -1;
    }
};
解法2:

水中的魚的博客中講述的http://fisherlei.blogspot.com/2013/11/leetcode-gas-station-solution.html。

在任何一個節點,其實我們只關心油的損耗,定義: 

diff[i] = gas[i] – cost[i]  0<=i <n 

那麼這題包含兩個問題: 

1. 能否在環上繞一圈? 

2. 如果能,這個起點在哪裏? 

第一個問題,很簡單,我對diff數組做個加和就好了,leftGas = ∑diff[i], 如果最後leftGas是正值,那麼肯定存在這麼一個起始點。如果是負值,那說明,油的損耗大於油的供給,不可能有解。得到第一個問題的答案只需要O(n)。 

對於第二個問題,起點在哪裏? 

假設,我們從環上取一個區間[i, j], j>i, 然後對於這個區間的diff加和,定義 

sum[i,j] = ∑diff[k] where i<=k<j 

如果sum[i,j]小於0,那麼這個起點肯定不會在[i,j]這個區間裏,跟第一個問題的原理一樣。舉個例子,假設i是[0,n]的解,那麼我們知道 任意sum[k,i-1] (0<=k<i-1) 肯定是小於0的,否則解就應該是k。同理,sum[i,n]一定是大於0的,否則,解就不應該是i,而是i和n之間的某個點。所以第二題的答案,其實就是在0到n之間,找到第一個連續子序列(這個子序列的結尾必然是n)大於0的。 

至此,兩個問題都可以在一個循環中解決。 

class Solution {
public:
    int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
        int len = gas.size();
        if(len!=cost.size()){
            return -1;
        }
        vector<int> dif(len);
        int left = 0;
        for(int i=0; i<len; i++){
            dif[i] = gas[i] - cost[i];
            left += dif[i];
        }
        if(left<0){
            return -1;
        }
        int startIndex = 0;
        int sum = 0;
        for(int i=0; i<len; i++){
            sum += dif[i];
            if(sum < 0){
                startIndex = i+1;
                sum = 0;
            }
        }
        return startIndex;
    }
};



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