这道题目我一开始用暴力解法一个个算来着,但果然超时了。然后看了la神的图像法解题思路。
不要被这个不同起点所蒙蔽,因为每个站点给你的油和你要花费的油是固定的,那么其实你油箱容量的起伏(在不同站点的差值)其实都是一样的。只不过从有的点开始的话,你的油量会走到 0 以下导致无法前进。而找到题解的过程,就是找到这个容量图像上最低的那个点,并从那个点开始作为起点就好了,也就是将整个图像向上平移。
这样的好处就是只需要经过一次计算,就可以找到最低点了,复杂度大大降低。
const canCompleteCircuit = (gas, cost) => {
const len = gas.length;
let tank = 0;
let lowest = 0;
let start = 0;
for (let i = 0; i < len; i++) {
// calculate the current amount of gas in the tank
tank += gas[i] - cost[i];
// if there is a new lower value
// update the lowest and set the next index to be the start
if (tank < lowest) {
lowest = tank;
start = i + 1;
}
}
// this is important!
// because if the total cost is larger than the total gas
// it is impossible to find a valid start
if (tank < 0) {
return -1;
}
return start === len ? 0 : start;
};