Lintcode187 solution 题解

本文探讨了一道经典的算法问题——环路加油站问题。该问题要求找出一个起点,使得一辆油箱无限大的汽车能够从该加油站出发,绕环路一周并回到起点。文章详细解释了解决该问题的思路和步骤。

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

 

【题目描述】

There areNgas stations along a circular route, where the amount of gas at station 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.

Notice:The solution is guaranteed to be unique.

在一条环路上有N个加油站,其中第i个加油站有汽油gas[i],并且从第_i_个加油站前往第_i_+1个加油站需要消耗汽油cost[i]。

你有一辆油箱容量无限大的汽车,现在要从某一个加油站出发绕环路一周,一开始油箱为空。

求可环绕环路一周时出发的加油站的编号,若不存在环绕一周的方案,则返回-1。

【注】:数据保证答案唯一。

【题目链接】

www.lintcode.com/en/problem/gas-station/

【题目解析】

这题的意思就是求出从哪一个油站开始,能走完整个里程,并且这个结果是唯一的。

首先我们可以得到所有油站的油量totalGas,以及总里程需要消耗的油量totalCost,如果totalCost大于totalGas,那么铁定不能够走完整个里程。

如果totalGas大于totalCost了,那么就能走完整个里程了,假设现在我们到达了第i个油站,这时候还剩余的油量为sum,如果 sum + gas[i] - cost[i]小于0,我们无法走到下一个油站,所以起点一定不在第i个以及之前的油站里面(都铁定走不到第i + 1号油站),起点只能在i + 1后者后面。

【参考答案】

www.jiuzhang.com/solutions/gas-station/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值