[LeetCode]Gas Station

本文探讨了一道关于环形路线上加油站的算法问题。给定每个加油站的油量及从一站到下一站所需的油耗,文章提供了一个解决方案,用于确定是否能够完成一次完整的环路旅行,并指出起始加油站的位置。采用O(N)的时间复杂度和O(1)的空间复杂度,确保了解决方案的高效性。

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


本题难度Medium。

【题意】
如果有解,解是唯一的;如果无解,返回-1。

【复杂度】
时间 O(N) 空间 O(1)

【思路】
sum表示当前 station i1 作为起点时到达station i2 的油量;用j标记起点station的前一个station;用total判断整个数组是否有解。有解就通过j来得到起点,没有解就返回-1

【附】
如果本题有解,而某个点上sum<0,就说明其中必然有且只有1个station的gas“特别地多”,但是目前还没遍历到该station。能这样判断的原因就在于如果有解就是唯一的解。

【代码】

public class Solution {
    public int canCompleteCircuit(int[] gas, int[] cost) {
        //require
        int size=gas.length;
        int j=-1,sum=0,total=0;
        //invariant
        for(int i=0;i<size;i++){
            sum+=gas[i]-cost[i];
            total+=gas[i]-cost[i];
            //sum<0,说明从i1到i2都不可以作为起点,因此选下一个为起点
            if(sum<0){
                sum=0;
                j=i;
            }
        }
        //ensure
        return total<0?-1:j+1;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值