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.

思路分析:这题O(n^2)的解法容易想到,可以从零开始,不断试探向后面走,如果发现油量为负数,则改变起点为1,以此类推。但是这种解法会超时。这题有O(n)的解法,也就是采用双指针的思路,用i来标记当前的start point,j表示当前car到达的station,用sum来表示car剩下多少油量,那么从i开始,j是当前station的指针,sum += gas[j] – cost[j] (从j站加了油gas[j],再算上从i开始走到j剩的油sum,减去从j走到j+1的油耗cost[j],这里是试探是否能走到j+1)。如果sum < 0,就说明从i开始是不行的,需要更新start point i。那能不能从i到j中间的某个位置开始呢?假设能从k (i <=k<=j)走,由于sum[i..j] < 0,如果sum[k..j] >=0,说明sum[i..k – 1]<0,那从i开始到k肯定无法到达,也就是说,从k出发,肯定是没有办法回到k的(至少i到k无法走)。所以一旦sum<0,应该把i赋成j + 1,sum归零。最后用total表示能不能走一圈。对于环状数组或者链表,经常可以用双指针的思路得到巧妙的解法,类似的题目还有判断一个链表是否存在circle,也可以用双指针的思路得到O(n)的解法。

这题参考了这个题解,需要更加深入思考反复理解。

AC Code

public class Solution {
    public int canCompleteCircuit(int[] gas, int[] cost) {
        int i = 0;
        int j = 0;
        int sum = 0; 
        int total = 0;
        
        while(j < gas.length){
            int leftGas = gas[j] - cost[j];
            if(sum + leftGas < 0){
                i = j + 1;
                sum = 0;
            } else {
                sum += leftGas;
            }
            j++;
            total += leftGas;
        } 
        if(total >= 0) return i;
        else return -1;
      
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值