【leetcode】134. 加油站

107 阅读1分钟

image.png

找到从某一点出发,可以走完全程
对于这一题的思考,如果走在某一点时,gas没有了,那么就不能走了,如果走在某一点,这里的gas是最少的,那么可以从这一点作为出发点。

var canCompleteCircuit = function (gas, cost) {
    let minGas = Infinity
    let index = 0
    let rest = 0
    for (let i = 0; i < gas.length; ++i) {
        rest += gas[i] - cost[i]
        // 记录剩余gas最少的站点
        if (rest < minGas) {
            minGas = rest
            index = i
        }
    }
    return rest < 0 ? -1 : (index + 1) % gas.length
};

下面这段代码的思路是记录总耗油剩余totalGas
如果小于0,那么肯定不能走到终点
currentGas,目前剩余油量,如果小于0,那么走不到后面,则记录当前的索引(从此处开始),

var canCompleteCircuit = function (gas, cost) {
    let totalGas = 0
    let currentGas = 0
    let startIndex = 0
    for (let i = 0; i < gas.length; ++i) {
        totalGas += gas[i] - cost[i]
        currentGas += gas[i] - cost[i]
        if (currentGas < 0) {
            startIndex = i + 1
            currentGas = 0
        }
    }
    return totalGas >= 0 ? startIndex : -1
};