【LeetCode】134. 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.


思路

此题我是用 O(n2) 的解法做的,我并没有想到特别好的办法。

但是仔细想想可以发现,一旦从点i开始,经过若干站后不能到达点j(j为i开始第一个不能到达的点),那么从点i到点j之间的任意一点开始都不可能到达点j。

没想明白?不要紧,我再重复一遍:如果从点i开始,经过若干站后不能到达点j,那么从点i到点j之间的任意一点开始都不可能到达点j。

原因是:假设i与j之间我们任选一点A,i到A的时候最差最差是剩0个油,这与从A开始的情况完全相同,i最差的情况都不能到j,那么从A开始当然不能到j了。

所以基于上述理由,一旦i开始不能到j,i与j之间的点我们就不必再试了,它们必然不能到j。

还有一个非常重要的点,就是一圈总的油如果加起来大于等于消耗的,那么一定可以转一圈。证明也比较容易,可以采用反证法。

综合利用上述两点,可以实现一个 O(n) 的解法


代码

int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
        int tank(0),total(0),start(0);
        for (int i=0;i<gas.size();++i){
            if ((tank=tank+gas[i]-cost[i])<0){
                start=i+1;
                total=total+tank;
                tank=0;
            }
        }
        return (total+tank<0)?-1:start;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值