zoukankan      html  css  js  c++  java
  • [LeetCode]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)的算法,就是对每个点能否到达终点进行模拟。

    还有一个O(n)的算法。代码如下,这种解法充分利用了题中只有一个唯一解(如果有解的话)的信息。思考一下:

    1.如果total<0则一定没有解,因为不管从哪个位置开始,一定无法通过最后一个加油站。

    1.如果total>=0一定有解,而且这个解一定是最后一个sum<0的下一个位置(j=i+1)。读者可以仔细思考一下为什么(tips:假设有k个sum<0的点,结合其他信息推断只有该点是有效起始位置)。

    代码

    public int canCompleteCircuit(int[] gas, int[] cost) {
            // Note: The Solution object is instantiated only once and is reused by each test case.
         int n=gas.length;
         if(n==0)
             return -1;
         int sum=0,total=0;
         int j=0;
         for(int i=0;i<n;i++)
         {
             sum+=(gas[i]-cost[i]);
             total+=(gas[i]-cost[i]);
             if(sum<0)
             {
                 j=i+1;
                 sum=0;
             }
         }
         return total>=0?j:-1;
        }
  • 相关阅读:
    无法定位程序输入点 ucrtbase.terminate 于动态链接库 api-ms-win-crt-runtime-|1-1-0.dll 上的解决方案
    .net 使用语音播放文字
    Firebird 数据库使用经验总结
    firebird 中的域
    WPF 中 OpenClipboard 失败问题
    Delphi Format 格式化数字
    画圆弧方法
    java.util.concurrent
    linux下软件安装方法
    基于java的http服务器
  • 原文地址:https://www.cnblogs.com/developerY/p/gasstation.html
Copyright © 2011-2022 走看看