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.

Note:
The solution is guaranteed to be unique.

题意解析:

题目大概就是说有一个环形的路线,路线上有很多分布的加油站,每个加油站的油量是```gas[i]```,然后你开一辆车,从某一个加油站出发,看看能否绕一圈,从一个加油站到下一个加油站需要的油量是‘’‘cost[i]’‘’。如果可以的话,就返回出发的那个加油站的下标```i```,不行的话就返回-1。

答案假定是唯一的。

首先按照正常思路可以想到一个暴力解决的方法,就是去循环遍历每个结点,试着环绕一圈,代码如下:

public class Solution {
    public int canCompleteCircuit(int[] gas, int[] cost) {
        for(int i = 0; i < gas.length; i++){
            int currentGas = gas[i];
            int j = i;
            while(currentGas >= cost[j]){
                //能够到达下一站
                currentGas -= cost[j];
                j = (j+1) % gas.length;
                if(j == i){
                    return i;
                }
                currentGas += gas[j];
            }
        }
        return -1;
    }
}
上述代码复杂度O(n^2),思路简单清晰,然而,难度是Medium的题目怎么可能就这么解决呢?

提交代码,超时了。很尴尬,只能想一些巧妙的方法。

这里应该这么想,想要完成全程其实只要满足两个条件即可,第一个是,所有的gas和大于cost和。第二个就是,当前油量可以到达下一站。第二个条件的实现有点抽象,我会在代码里解释,并在后面给出更详细的说明,代码如下:

public class Solution {
    public int canCompleteCircuit(int[] gas, int[] cost) {
        int sum = 0;
        int total = 0;
        int j = 0;
        for(int i = 0; i < gas.length; i++){
            sum += gas[i] - cost[i];
            total += gas[i] - cost[i];
            if(sum < 0){
                //说明此时汽车无法到达下一站,所以之前所有的i包括当前i都不能作为起点。起点只可能是后面的某个值
                j = i + 1;
                sum = 0;
            }
        }
        if(total >= 0){
            return j;
        }else{
            return -1;
        }
    }
}
这个算法用total来表示总油量是足够支持到下一站的,sum则表示能不能到达下一站,可以证明:如果```gas[i] >= cost[i]```,则可以出发,并且带有储存油量,如果一直保持了 ```gas[i] >= cost[i]```这个条件,则说明储存的油量是在不断增加的,所以如果某一次出现```currestGas + gas[i] < cost[i]```,不仅说明不能从这一站出发,还说明了不能从之前的任一站出发。所以就先假定下一站是可以出发的。


代码复杂度是O(n),运行时间也只有1ms,已经是最优算法了,至于前面的0ms,大概是以前的数据或者是在服务器性能极好的时候进行了提交,导致时间短到离谱。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值