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;
};