zoukankan      html  css  js  c++  java
  • 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;
        }
    }
  • 相关阅读:
    对于对象的要求:高内聚、低耦合,这样容易拼装成为一个系统
    为什么要使用面向对象
    什么是对象:EVERYTHING IS OBJECT(万物皆对象)
    文件 I/O 问题
    如果可能的话,使用 PC-Lint、LogiScope 等工具进行代码审查
    把编译器的选择项设置为最严格状态
    尽量不要使用与具体硬件或软件环境关系密切的变量
    尽量使用标准库函数
    如果原有的代码质量比较好,尽量复用它
    不要设计面面俱到、非常灵活的数据结构
  • 原文地址:https://www.cnblogs.com/jasminemzy/p/9668794.html
Copyright © 2011-2022 走看看