[LeetCode][Java] Gas Station

來源:互聯網
上載者:User

標籤:leetcode   java   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個加油站,在位置 i 上的汽油的數目為gas[i].

你有一個汽車,這個汽車的油箱是無限容量的,它從加油站 i 到 加油站 (i+1)需要耗費的汽油數為cost[i].開始這段旅程的時候,你的起始狀態是在加油站中的一個,油箱為空白的.

若一次性完成整個的圓形路途,返回你的其實加油站的序號,若不能完成整個路途,返回-1.

注意:

解決方案保證是唯一的.

演算法分析:

參考部落格:http://pisxw.com/algorithm/Gas-Station.html

暴力解法比較好想,但是逾時了。就是從每一個站開始,一直走一圈,累加過程中的淨餘的油量,看它是不是有出現負的,如果有則失敗,從下一個站開始重新再走一圈;如果沒有負的出現,則這個站可以作為起始點,成功。可以看出每次需要掃描一圈,對每個站都要做一次掃描,所以時間複雜度是O(n2)。

給出提高的演算法:方法主要思想是把這個圈劃分成一個個的負序列,以及一個正序列(如果存在的話)。從任意一個站出發,我們可以累加油的淨餘量,如果出現負的,序列結束,開啟一個新的,並且證明舊的這個序列的起點不能作為起點,因為會出現負油量,不能繼續前進。而且不僅這個負序列的起點不能作為起點,負序列中的任意一點都不能作為起點。具體證明不給出了,感興趣的可以參考上面的部落格。

簡述演算法:若 i = k時,sum小於0,表示車無法到達第k個加油站,必須從下一個加油站開始出發,total來判斷是否能夠迴圈一圈。

AC代碼:

<span style="font-family:Microsoft YaHei;font-size:12px;">public class Solution {    public int canCompleteCircuit(int[] gas, int[] cost)     {        if(gas==null || cost==null || gas.length==0 || cost.length==0)            return -1;        int sum=0;//到達當前加油站的總淨容量        int total=0;//整個完成一圈的總容量        int pointer=0;//定義起點        for(int i=0;i<gas.length;i++)        {            int diff=gas[i]-cost[i];            sum+=diff;            total+=diff;            if(sum<0) //到達該節點油不夠。那麼這之間的節點都不能作為起點,因為這之間的節點都是正淨容量。            {                sum=0;                pointer=i+1;            }        }        return total>=0?pointer:-1;    }}</span>

著作權聲明:本文為博主原創文章,轉載註明出處

[LeetCode][Java] Gas Station

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.