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 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.

 解答:最简单的解题思路是逐个检查每个节点 i,尝试从i开始的每个节点上是否满足剩余汽油量surplus > 0. 如果找到一个满足条件的节点,则算法结束;如果遍历完所有结点,仍然没有找到,就返回-1. 这个算法的复杂度为O(n * n). 结果会超时。

要找到一个更优的算法,就要考虑在上面的算法上是否有冗余的步骤。显然,每个节点在检查是否满足条件的过程中是彼此独立的,并没有用到上一个节点的结果。我们考虑能否在下一步计算过程中,利用到已经知道的信息。这就需要对问题进行更加深入的分析。

下面给出这个结论:

假设从节点i 出发,可以到达的节点是 j 并且 j != i。由于可以从i 开始,因此 gas[i] - cost[i] > 0. 如果从 i  到 j 中间的任何一个节点出发,结果都不会到达比j 更远的节点。

这个结论很容易证明,这里就略去了。证明中主要依据是在每个节点处都要保证剩余汽油量surplus >=0.

有了这个结论,就可以得到复杂度为O(n)的算法。对于每个节点,只需要遍历一次就可以了。主要思路为:从下标为0的节点出发,假设可以到达节点 j 。如果 j 不等于 0 ,则说明以下标为0的节点出发,不能满足条件;但是,也不必遍历0 到j 之间的节点。最初begin = 0。如果当前的begin不满足条件,则让begin = (begin - 1 + numOfGasStation) % numOfGasStation。主要思想是如果当前节点出发不能满足条件,则说明过程中剩余油量不足以行驶完全程,将上一个节点作为当前节点,如果上面有多余的汽油余量,就可以让车走的更远。 count的作用是记录已经遍历的节点数,如果所有结点都遍历完,但是仍然没有找到满足条件的节点,则返回 -1。

class Solution {
public:
    int canCompleteCircuit(vector<int> &gas, vector<int> &cost) {
       
        int numOfGasStation = gas.size();
        int surplus = gas[0] - cost[0];
        int begin = 0;
        int count = 1;
        int next = begin + 1;
       
        if(count == numOfGasStation && surplus >= 0)
            return 0;
       
        while(count < numOfGasStation){
           
            if(surplus >= 0 && surplus + (gas[next] - cost[next]) >= 0){
                surplus += (gas[next] - cost[next]);
            }
            else{
                begin = (begin - 1 + numOfGasStation) % numOfGasStation;
                surplus += (gas[begin] - cost[begin]);
                count++;
                continue;
            }
            next = (next + 1) % numOfGasStation;
            count++;
               
        }
        if(surplus >= 0)
            return begin;
        else
            return -1;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值