题目描述:

在一条环路上有 N 个加油站,其中第 i 个加油站有汽油 gas[i] 升。
你有一辆油箱容量无限的的汽车,从第 i 个加油站开往第 i+1 个加油站需要消耗汽油 cost[i] 升。你从其中的一个加油站出发,开始时油箱为空。
如果你可以绕环路行驶一周,则返回出发时加油站的编号,否则返回 -1。

解析:

图片说明

1.首先判断总加油量和总油耗量的大小,如果总加油量小于总油耗量,则返回-1
2.定义一个变量currentGas表示当前车油量,遍历循环每个站点,计算当前车油量
如果当前车油量小于0,则使currentGas等于0,然后从下一个站点再开始
如果当前车油量大于等于0,则继续遍历循环站点
3.用start记录站点,最后返回start即可

Java:

public int canCompleteCircuit(int[] gas, int[] cost) {
        int totalGas = 0;
        int totalCost = 0;
        for(int i = 0; i < gas.length; i++) {
            totalGas += gas[i];
            totalCost += cost[i];
        }
        if(totalGas < totalCost) {
            return -1;
        }
        int currentGas = 0;
        int start = 0;
        for(int i = 0; i < gas.length; i++) {
            currentGas = currentGas - cost[i] + gas[i];
            if(currentGas < 0) {
                currentGas = 0;
                start = i + 1;
            }
        }
        return start;
    }

JavaScript:

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