LeetCode OJ - Gas Station

本文探讨了一种时间复杂度为O(n)、空间复杂度为O(1)的高效算法来解决环形油站问题。通过观察特定的油站策略,算法能够快速确定汽车是否可以完成一圈行驶,若能则返回起始油站位置,否则返回-1。提供了一个实用的AC代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

---恢复内容开始---

这道题考察的可能偏向逻辑的思考能力。

最有效的方法是时间复杂度为O(n),空间复杂度为O(1).这种高效算法,参考一个前辈的思想:“My linear solution based on a observation that, if you stops at certain gas station, the gas stations previous to the station you stop must not be a valid starting point. ”

意思是说从某个station开始,如果不能回到这个station,而是停在中间某一个station,那么从start到stop的这些station都不能作为汽车的起点。

下面是AC代码:

/**
     * 
     * @param gas
     * @param cost
     * @return Return the starting gas station's index if you can travel around
     *  the circuit once, otherwise return -1.
     */
    public int canCompleteCircuit(int[] gas, int[] cost)
    {
        int left = 0;
        int start=0, i;
        int N = gas.length;
        while(true)
        {
            i = start;
            left = 0;
            while(left+gas[i%N]-cost[i%N]>=0)
            {
                left = left+gas[i%N]-cost[i%N];
                i++;
                if(i%N == start%N)
                    return i%N;
            }
            if(i>N-1)
                return -1;
            start = ++i;    
        }
    }

 

---恢复内容结束---

转载于:https://www.cnblogs.com/echoht/p/3690192.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值