LeetCode刷題筆記(貪心):gas-station



題目描述

There are N gas stations along a circular route, where the amount of gas at station i isgas[i].

You have a car with an unlimited gas tank and it costscost[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到下一站(i + 1)需要花費天然氣。 你從一個加油站開始,開始時郵箱爲空。 如果您可以在電路上巡迴一次,則返回啓動加油站的索引,否則返回-1。 注意:解決方案保證是唯一的。

解題思路

從start出發,如果油量足夠,可以一直向後走end++;油量不夠的時候,
start向後退,最終start == end的時候,如果有解一定是當前start所在位置。

因爲是個環,所以我們將最後一個元素設置爲起點,第一個元素設置爲start下一點,這樣可以用統一的判斷條件start < end來作爲循環的條件,當start和end兩者相等時,循環結束。

C++版代碼實現

class Solution {
public:
    int canCompleteCircuit(vector<int> &gas, vector<int> &cost) {
        if(gas.size() <= 0 || cost.size() <= 0)
            return -1;

        int start = gas.size() - 1;
        int end = 0;
        int sum = gas[start] - cost[start];
        while(start > end){
            if(sum >= 0){
                sum += gas[end] - cost[end];
                ++end;
            }
            else{
                --start;
                sum += gas[start] - cost[start];
            }
        }
        return sum >= 0 ? start : -1;
    }
};

系列教程持續發佈中,歡迎訂閱、關注、收藏、評論、點贊哦~~( ̄▽ ̄~)~

完的汪(∪。∪)。。。zzz

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