LeetCode: Gas Station [134]

來源:互聯網
上載者:User

標籤:leetcode   演算法   面試   

【題目】

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站駛到下一站i+1需要消耗的油量由cost[i+1]給出
    找出從那個加油站始發能夠正好跑完一圈。返回加油站的索引位,如果找不到返回-1
    
    題目保證,解是唯一的。


【思路】

    1. 先計算要行駛到下一個加油站,每站至少需要剩油多少,即能夠從當前節點可達下一站的臨界條件
    2. 選擇那些剩油需求<=0的加油站作為起點,依次判斷

    


【代碼】
class Solution {public:    int canCompleteCircuit(vector<int> &gas, vector<int> &cost) {        int size=gas.size();        if(size==0)return -1;//注意size=1也是需要考慮。這裡好大一個坑,竟然真有自己駛到自己這種荒謬的case        vector<int> gasRemainNeed;                for(int i=0; i<size; i++){            gasRemainNeed.push_back(cost[i]-gas[i]);        }        int start=0;int p=start;int remain=0;        while(start<size){            while(remain>=gasRemainNeed[p%size]){    //判斷當前汽車的剩油量夠不夠跑到下一站,如果能跑就不斷跑下去,直到跑不下去為止                remain-=gasRemainNeed[p%size];//計算駛到下一站的剩油量                p++;//遊標指向下一站                if(p%size==start)return start;   //如果已經跑完一圈,返回            }//start向後移動,並不斷更新油箱中的剩油,直到剩油量能使車從p駛到p+1while(start<size && start<p && remain<gasRemainNeed[p%size]){remain+=gasRemainNeed[start];start++;}//如果p指標正好指到start上,則兩個遊標同時向後移動一位if(start==p){start++; p++;}        }        return -1;    }};


相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.