欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

LeetCode 面试经典 150 题 134. 加油站

最编程 2024-07-08 08:07:40
...

题目

在一条环路上有 n 个加油站,其中第 i 个加油站有汽油 gas[i] 升。

你有一辆油箱容量无限的的汽车,从第 i 个加油站开往第 i+1 个加油站需要消耗汽油 cost[i] 升。你从其中的一个加油站出发,开始时油箱为空。

给定两个整数数组 gas 和 cost ,如果你可以按顺序绕环路行驶一周,则返回出发时加油站的编号,否则返回 -1 。如果存在解,则 保证 它是 唯一 的。

思路:从x出发,到y走不下去了。那么对于x到y中的所有节点z,如果从z出发,一定会在y处卡住。应用这个结论,我们在遍历的时候,不需要遍历x到y中的节点了,只需要从走不下去的节点y的下一个节点作为起始遍历即可。

代码

class Solution {
    public int canCompleteCircuit(int[] gas, int[] cost) {
        int n = gas.length;
        // 起点i
        int i = 0;
        while (i < n) {
            int sumOfGas = 0, sumOfCost = 0;
            // 记录经过的车站数
            int count = 0;
            while (count < n) {
                int j = (i + count) % n;
                sumOfGas += gas[j];
                sumOfCost += cost[j];
                // 走不下去
                if (sumOfCost > sumOfGas) {
                    break;
                }
                count++;
            }
            if (count == n) 
                return i;
            else 
                i = i + count + 1;
        }
        return -1;
    }
}

性能:时间复杂度O(n)   空间复杂度O(1)