【贪心算法】Find the first circular tour that visits all petrol pumps

这道题目要求在环形路线上找到第一个能遍历所有加油站的起点,车辆油箱无限但每站间有油耗。通过利用贪心算法,使用队列存储当前行程,依次加入加油站直到完成环路或汽油不足。若汽油不足,则回退并继续尝试。
摘要由CSDN通过智能技术生成

题目:在一条环路上有 N 个加油站,其中第 i 个加油站有汽油 gas[i] 升。

你有一辆油箱容量无限的的汽车,从第 i 个加油站开往第 i+1 个加油站需要消耗汽油 cost[i] 升。你从其中的一个加油站出发,开始时油箱为空。

如果你可以绕环路行驶一周,则返回出发时加油站的编号,否则返回 -1。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/gas-station
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

An efficient approach is to use a Queue to store the current tour. We first enqueue first petrol pump to the queue, we keep enqueueing petrol pumps till we either complete the tour, or the current amount of petrol becomes negative. If the amount becomes negative, then we keep dequeuing petrol pumps until the queue becomes empty.

The amount of petrol that every petrol pump has.
Distance from that petrol pump to the next petrol pump.
思路:
用totalGas保存经过的加油站的所有汽油
用currentGas保存当前汽油。要是curretGas < 0的时候,重置currentGas.

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

	int currentGas = 0;
	int totalGas = 0;
	int startStation = 0;
	
	for(int i = 0; i < len; i++) {
		currentGas += gas[i] - cost[i];
		totalGas += gas[i] - cost[i];
		if(currentGas < 0) {
			currentGas = 0;
			//i+1不影响,只是保存一个个变量而已
			startStation = i + 1;
	}   
	}
	return totalGas >= 0? startStation : -1;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值