C++實現LeetCode(134.加油站問題)

[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的總量要大於cost的總量,這樣才會有起點的存在。假設開始設置起點start = 0, 並從這裡出發,如果當前的gas值大於cost值,就可以繼續前進,此時到下一個站點,剩餘的gas加上當前的gas再減去cost,看是否大於0,若大於0,則繼續前進。當到達某一站點時,若這個值小於0瞭,則說明從起點到這個點中間的任何一個點都不能作為起點,則把起點設為下一個點,繼續遍歷。當遍歷完整個環時,當前保存的起點即為所求。代碼如下:

解法一:

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

我們也可以從後往前遍歷,用一個變量mx來記錄出現過的剩餘油量的最大值,total記錄當前剩餘油量的值,start還是記錄起點的位置。當total大於mx的時候,說明當前位置可以作為起點,更新start,並且更新mx。為啥呢?因為我們每次total加上的都是當前位置的油量減去消耗,如果這個差值大於0的話,說明當前位置可以當作起點,因為從當前位置到末尾都不會出現油量不夠的情況,而一旦差值小於0的話,說明當前位置如果是起點的話,油量就不夠,無法走完全程,所以我們不更新起點位置start。最後結束後我們還是看totoa是否大於等於0,如果其小於0的話,說明沒有任何一個起點能走完全程,因為總油量都不夠,參見代碼如下:

解法二:

class Solution {
public:
    int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
        int total = 0, mx = -1, start = 0;
        for (int i = gas.size() - 1; i >= 0; --i) {
            total += gas[i] - cost[i];
            if (total > mx) {
                start = i;
                mx = total;
            }
        }
        return (total < 0) ? -1 : start;
    }
};

類似題目:

Reaching Points

Transform to Chessboard

Cheapest Flights Within K Stops

參考資料:

https://leetcode.com/problems/gas-station/discuss/42568/Share-some-of-my-ideas.

https://leetcode.com/problems/gas-station/discuss/42656/8ms-simple-O(n)-c++-solution

到此這篇關於C++實現LeetCode(134.加油站問題)的文章就介紹到這瞭,更多相關C++實現加油站問題內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: