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<int>& gas, vector<int>& 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的寻找,采用本题的方法而不是从第一个到最后一个点分别尝试。降低了时间复杂度。

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

jackson61

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值