[LeetCode]Gas Station

解决环形路线上的加油问题,确保车辆能绕行一周。分析条件并提供算法思路及Java实现。

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

题目分析

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.

现在有N个加油站形成环形,每个加油站储油gas[i]。现在有一辆车没有储油限制,并且它从加油站i到加油站i+1耗费油cost[i],问你能否找到一个加油站使其作为起点,你可以走完一圈。如果没有返回-1;

解题思路


由上图我们来进行分析,我们定义reminder表示从一个站点到下一个站点时剩余的油量,初始为0。
如果要满足题目要求,则应需要满足以下条件:
  1. 对于每一段路程,reminder>=0;
  2. 对于每一段路程,remainder + gas[j % len] >= cost[j % len];
  3. 若想完成一圈,则应从起始站点i环绕一圈再走到i,且满足上述的两点;
这时我们很容想到通过循环n次,并在每次循环中开始遍历,看能否满足上述3点。这样想是非常正确的,但是你是否觉得有点问题?
对,这样做会超时,为什么呢?
我们来考虑,如果从0到i走不通,在i处中断,那么从1、2、3、i-1到i能否走通呢?答案是否定的,仔细想明白这一点我们就可以简化循环,节省时间。具体请看代码。

代码

public int canCompleteCircuit(int[] gas, int[] cost) {
        int len = gas.length;
		int remainder = 0;

		for (int i = 0; i < len; i++) {
			int j = i;
			while (j != len + i) {
				if (remainder >= 0 && remainder + gas[j % len] >= cost[j % len]) {
					remainder = remainder + gas[j % len] - cost[j % len];
					j++;
				} else {
				    i = j;
					break;
				}
			}
			if (j == len + i) {
				return i;
			}
		}
		return -1;
    }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值