• leetcode134


    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 in the clockwise direction, otherwise return -1.
    Note:
    * If there exists a solution, it is guaranteed to be unique.
    * Both input arrays are non-empty and have the same length.
    * Each element in the input arrays is a non-negative integer.
    Example 1:
    Input:
    gas = [1,2,3,4,5]
    cost = [3,4,5,1,2]
    Output: 3
    Explanation:
    Start at station 3 (index 3) and fill up with 4 unit of gas. Your tank = 0 + 4 = 4
    Travel to station 4. Your tank = 4 - 1 + 5 = 8
    Travel to station 0. Your tank = 8 - 2 + 1 = 7
    Travel to station 1. Your tank = 7 - 3 + 2 = 6
    Travel to station 2. Your tank = 6 - 4 + 3 = 5
    Travel to station 3. The cost is 5. Your gas is just enough to travel back to station 3.
    Therefore, return 3 as the starting index.

    贪婪法。O(n)
    遍历一次数组即可。遍历过程中如果发现tank<0失败了,你就归零tank从下一个点继续开始出发。最后一次尝试的出发点就是答案。
    原因是本题有两个属性:
    1 如果总的gas - cost小于零的话,那么没有解。
    2 如果前面所有的gas - cost加起来小于零,那么前面所有的点都不能作为出发点。
    第二点的原因:从0走到n,第n步挂了的话。0~n-1步前面都还走的好好的是因为他们一直在正累积,如果缺了前面0~k任意哪一块,都是少了一块正累积,走到这一步的时候更要挂了。所以前面每一步都不可能,答案在后面或者根本没答案。

    实现:

    class Solution {
        public int canCompleteCircuit(int[] gas, int[] cost) {
            int start = 0;
            int tank = 0, total = 0;
            for (int i = 0; i < gas.length; i++) {
                tank += gas[i];
                tank -= cost[i];
                total += gas[i];
                total -= cost[i];
                if (tank < 0) {
                    start = i + 1;
                    tank = 0;
                }
            }
            return total >= 0 ? start : -1;
        }
    }
  • 相关阅读:
    命令行中邮件的收发
    关于location对象
    正则表达式
    一家初创公司的 CTO 应当做什么?
    移动数据网络质量的国家奖牌榜
    MFQ&PPDCS测试分析和测试设计框架l学习记录
    Python学习笔记之基本语法学习1
    《用Python做HTTP接口测试》学习感悟
    我的中台的理解
    中台与平台的区别
  • 原文地址:https://www.cnblogs.com/jasminemzy/p/9668794.html
Copyright © 2020-2023  润新知