leetcode题目:gas-station 使用start/end方法的个人理解

题目:There are N gas stations along a circular route, where the  amount of gas at station i isgas[i].  You have a car with an unlimited gas tank and it costscost[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.

最近在刷leetcode的题目,看到这道题我用贪心,常规方法循环解可以ac。看别人的想法,用start和end来思考,挺有意思的,感觉特别巧妙,怕自己忘,写在这里吧。

代码

int canCompleteCircuit(vector<int> &gas, vector<int> &cost) {
        
             
        int n=gas.size();
        int end=0;
        int start=n-1;
        int sum=gas[start]-cost[start];
        while(start>end){
            if(sum>0){
                sum+=gas[end]-cost[end];
                ++end;
            }
            else{
                --start;
                sum+=gas[start]-cost[start];
            }
        }
        return sum>=0?start:-1;
    }

接下来解释下这种方法为什么可行。假设有5个节点吧,gas分别是 a1~a5 ,cost分别是b1~b5 。 如图顺时针考虑。

 外循环是start和end相等时结束,就是他俩相遇了。初始让start在a5 , end在a1。我只假设3中情况:1、在a5相遇。2、在a1相遇。3、在中间相遇。


1、a5相遇
    在a5相遇是因为end顺时针走到a5,怎么走的呢?第一次sum=a5-b5,因为sum>=0,end才能往前走,说明从a5走到a1的油足够,下一次end再往前走,说明上一次省的油(sum中保存)加上a1-b1 的和还是>=0,这个车可以一直走下去。直到最后sum=(车走到a4处剩余的油)+(a4-b4),退出循环,只要判断这个sum是不是>=0,就知道车从a5出发能不能转一圈回来了。
2、在a1相遇
    在a1相遇需要start不断减1减到a1处,为什么start要递减呢?因为判断了sum<0了,小于0说明第一次从a5出发到a1的油不够了,那车就从a4出发吧(start减1),看看从a4出发能不能剩油,同时剩的油能不能填补a5到a1那段不够的油,要是还不够,那start继续减1,看看从a3那出发行不行。结果呢,一直到a2都不够,那最后sum=(在a2出发不够的油)+(a1-b1),在end处重合,退出循环。然后判断一下sum够不够,够的话就从a1出发。
3、在中间相遇(假设就在a3相遇吧)
    在a3相遇就是说end要顺时针走到a3,start要逆时针走到a3。end++的解释和start--的解释都在上面了。


最后加一句其实,总的油量只要大于等于总的花费量,就一定存在一个点让车能走一圈。每次退出循环的sum都等于总油量减去总花费。如果sum<0,那就不存在,否则,退出循环的那个点就是可以的出发点。当然可能出发点有多个,这种方法就看初始位置选在哪里了。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值