leetcode--17. 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.

沿環(huán)形路線有N個加油站,其中第 i 站的煤氣量為gas[ i ]。你有一輛有一個無限制油箱的汽車,從 i 站到下一站(i+1)要花費大量的汽油。你從一個加油站并且初始油箱為空開始旅程。如果你可以繞環(huán)路一次,返回啟程加油站的索引,否則返回-1。
注意:解決方案保證是唯一的。

思路:
用最后一個點作為起點,當(dāng)油量夠時則end++,當(dāng)油量不夠就start后退一個直至到0,換起點后不需計算后續(xù)點,只需要計算剛才結(jié)余即可

public class Solution {
    public int canCompleteCircuit(int[] gas, int[] cost) {
        int start = gas.length - 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;
    }
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi閱讀 7,854評論 0 10
  • 第一個VR應(yīng)用 之前我們已經(jīng)將Oculus的開發(fā)包導(dǎo)入到空工程中了,現(xiàn)在我們來構(gòu)建第一個桌面VR的示例。開發(fā)包中已...
    小太陽會發(fā)光諾閱讀 324評論 0 0
  • 奧登爺爺家的四個孩子又來到了“神秘農(nóng)場”,他們在那里還遇到了老朋友邁克。邁克的爸爸死了,他和哥哥媽媽來到了...
    JacobTang閱讀 362評論 0 0
  • 我想有個能量補給站 賜予我力量 我想有個時光穿梭機 賜予我歲月與時光 我想有個金剛不壞身 賜予我無限的光陰與力量 ...
    大愛無痕閱讀 143評論 0 1

友情鏈接更多精彩內(nèi)容