• Gas Station


    题目:

    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, otherwise return -1.

    Note:
    The solution is guaranteed to be unique.

    这个题,一上来就想用穷举法做了。做法是,以每一个点作为起点,都试一次。复杂度O(n^2)。这个。。。不大好。其实我们重复计算了很多。

    比如,我们以 a 为起点,试图走 a + 1, a + 2,a + 3 ... 一直走到b。如果我们在计算过程中发现,a 根本到不了b。按照原来的方法,我们该以 a + 1为起点,再算一次看能不能到b。

    想想是不可能的。如果从a出发, 到a + 1点后,邮箱里有从a剩下的油(最不济刚好为空)。带着剩下的油都到不了b,你空着邮箱从头开始怎么可能。所以起点肯定不在a到b这段了。直接从b + 1开始算。

     1 public int canCompleteCircuit(int[] gas, int[] cost) {
     2         if (gas == null || cost == null || gas.length == 0 || cost.length == 0) {
     3             return -1;
     4         }
     5         int start = 0;
     6         int tank = 0;
     7         int sum = 0;
     8         for (int j = 0; j < gas.length; j++) {
     9             int diff = gas[j] - cost[j];
    10             if (tank + diff >= 0) {
    11                 tank += diff; 
    12             }else{
    13                 start = j + 1;
    14             }
    15         }
    16         for (int i = 0; i < gas.length; i++) {
    17             sum = sum + gas[i] - cost[i];
    18         }
    19         if (sum >= 0) {
    20             return start;
    21         }else{
    22             return -1;
    23         }
    24     }
  • 相关阅读:
    git创建版本库
    DataSet的加密解密
    在InstallShield中加密字符串,在C#中解密
    asp.net后台长时间操作时,向前台输出“请等待"信息的方法
    DataSet的加密解密(续)
    XXTEA加密算法的InstallShield 脚本实现
    c#如何监视文件或者文件夹的变化
    wpf制作毛玻璃效果按钮的代码
    WPF中用于Path的Geometry MiniLanguage
    如何在非英文环境中正确显示数字
  • 原文地址:https://www.cnblogs.com/gonuts/p/4418876.html
Copyright © 2020-2023  润新知