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.
遍歷的方法,是對(duì)的,但是超時(shí)了:

var canCompleteCircuit = function(gas, cost) {
    var start = 0;
    var num = gas.length;
    while (start<gas.length) {
        var remain = 0;
        for (let i = start; i < num; i++) {
            remain += gas[i] - cost[i];
            if (remain<=0)
                break;
        }
        if (remain>=0&&start===0) {
            return start;
        }
        if (remain<=0) {
            start++;
            continue;
        }
        for (var i = 0; i < start; i++) {
            remain += gas[i] - cost[i];
            if (remain<=0)
                break;
        }
        if (remain>=0&&i === start - 1)
            return start;
        start++;
    }
    return -1;
};

仔細(xì)想想,有兩點(diǎn):
如果油的總量大于需要花費(fèi)的總量,一定存在解。
如果一輛車(chē)從A開(kāi)始,到達(dá)不了B,那么從A和B之間任何一站開(kāi)始都到達(dá)不了B。
所以我們從頭開(kāi)始遍歷數(shù)組,并記錄油箱中的剩余,如果小于0了,那就意味著此次出發(fā)的點(diǎn)到不了當(dāng)前點(diǎn),得從當(dāng)前點(diǎn)的下一點(diǎn)出發(fā)。遍歷到最后,判定一下是否有唯一解,返回最后設(shè)定的起點(diǎn)。

var canCompleteCircuit = function(gas, cost) {
    var start = 0;
    var total = 0;
    var tank = 0;
    //if car fails at 'start', record the next station
    for(var i = 0;i < gas.length;i++) {
        tank = tank + gas[i] - cost[i];
        if(tank < 0) {
            start = i + 1;
            total += tank;
            tank = 0;
        }
    }
    return (total + tank < 0) ? -1 : start;
};
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

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