• 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 stationi 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. The solution is guaranteed to be unique.

    题目如上,核心是能不能转一圈以及起点的问题。

    这道题有2个部分需要解决。第一,能不能转一圈。这个问题比较简单的办法就是将所有的gas和cost分别加起来,比较大小,若gas的和更大些那么肯定可以转一圈。第二个问题就是起点在哪里。这个稍微复杂一些。

    假设i无法到达k点(i可以到达k-1),那么我们可以说任意的位于i~k的一点都无法到达k点,那么我们可以直接从k+1这个点开始继续研究起点的问题。这个思想是研究起点的关键。

    代码如下:

    class Solution {
    public:
        int canCompleteCircuit(vector& gas, vector& cost) {
            int start = 0, tank = 0, total = 0;                                   //start记录当前起点,tank记录当前gas和cost的差,total用于统计最终的gas和cost的差
            for(int i = 0; i < gas.size(); i++){
                tank = tank + gas[i] - cost[i];
                if (tank < 0){                                                            //即之前说的i无法到达k的情况
                    start = i + 1;
                    total += tank;                                                      //这一步将i~k的gas和cost的差计入total,减少工作量
                    tank = 0;                                                             //重置tank,因为起点也重置了
                }
            }
            total += tank;
            if (total >= 0){
                return start;
            }
            else{
                return -1;
            }
        }
    };

    本题是贪心算法的一个简单应用。核心是对start的寻找,采用本题的方法而不是从第一个到最后一个点分别尝试。降低了时间复杂度。

    如有不足,请读者留言赐教。

  • 相关阅读:
    【Web】CSS学习笔记
    企业进行媒体宣传的重要性
    azkban设置重试不起作用,且有的任务一直running,无日志
    Java计算机毕业设计视频网站的设计与实现源码+系统+数据库+lw文档
    场外个股期权标的有哪些?
    实用设计模式实战:工厂+策略
    centos7安装yum的暴力直接办法
    AD637使用笔记
    python提速N倍的小秘诀——这份工具清单请收好
    MFC中如何重绘CListCtrl的表头
  • 原文地址:https://blog.csdn.net/jackson61/article/details/128065132