• [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;
        }
  • 相关阅读:
    03_02_leetcode_11_盛最多的水
    03_01_跳跃表
    初学Java算法编程_Array List自己和官方文档的区别
    编译原理习题解析-第1章
    VS2019配置C+++mingW32配置
    自创理解绝对定位和相对定位的方法
    Solution -「洛谷 P7395」「CoE-I 2021C」弹珠游戏
    Solution Set -「ARC 113」
    Solution Set -「ABC 192」
    Solution Set -「CF 1486」
  • 原文地址:https://www.cnblogs.com/developerY/p/gasstation.html
Copyright © 2020-2023  润新知