LeetCode 题解工作台
总行驶距离
卡车有两个油箱。给你两个整数, mainTank 表示主油箱中的燃料(以升为单位), additionalTank 表示副油箱中的燃料(以升为单位)。 该卡车每耗费 1 升燃料都可以行驶 10 km。每当主油箱使用了 5 升燃料时,如果副油箱至少有 1 升燃料,则会将 1 升燃料从副油箱转移到主油箱…
2
题型
6
代码语言
3
相关题
当前训练重点
简单 · 数学·结合·模拟
答案摘要
我们可以模拟卡车的行驶过程,每次消耗 升主油箱中的燃料,行驶 公里。每当主油箱中的燃料消耗 升时,如果副油箱中有燃料,则将副油箱中的 升燃料转移到主油箱中。一直模拟到主油箱中的燃料消耗完为止。 时间复杂度 $O(n + m)$,其中 和 分别是主油箱和副油箱中的燃料数量。空间复杂度 。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数学·结合·模拟 题型思路
题目描述
卡车有两个油箱。给你两个整数,mainTank 表示主油箱中的燃料(以升为单位),additionalTank 表示副油箱中的燃料(以升为单位)。
该卡车每耗费 1 升燃料都可以行驶 10 km。每当主油箱使用了 5 升燃料时,如果副油箱至少有 1 升燃料,则会将 1 升燃料从副油箱转移到主油箱。
返回卡车可以行驶的最大距离。
注意:从副油箱向主油箱注入燃料不是连续行为。这一事件会在每消耗 5 升燃料时突然且立即发生。
示例 1:
输入:mainTank = 5, additionalTank = 10 输出:60 解释: 在用掉 5 升燃料后,主油箱中燃料还剩下 (5 - 5 + 1) = 1 升,行驶距离为 50km 。 在用掉剩下的 1 升燃料后,没有新的燃料注入到主油箱中,主油箱变为空。 总行驶距离为 60km 。
示例 2:
输入:mainTank = 1, additionalTank = 2 输出:10 解释: 在用掉 1 升燃料后,主油箱变为空。 总行驶距离为 10km 。
提示:
1 <= mainTank, additionalTank <= 100
解题思路
方法一:模拟
我们可以模拟卡车的行驶过程,每次消耗 升主油箱中的燃料,行驶 公里。每当主油箱中的燃料消耗 升时,如果副油箱中有燃料,则将副油箱中的 升燃料转移到主油箱中。一直模拟到主油箱中的燃料消耗完为止。
时间复杂度 ,其中 和 分别是主油箱和副油箱中的燃料数量。空间复杂度 。
class Solution:
def distanceTraveled(self, mainTank: int, additionalTank: int) -> int:
ans = cur = 0
while mainTank:
cur += 1
ans += 10
mainTank -= 1
if cur % 5 == 0 and additionalTank:
additionalTank -= 1
mainTank += 1
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(mainTank + additionalTank) since each liter may trigger a transfer check. Space complexity is O(1) because only counters for distance and remaining fuel are needed. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Asks about simulating incremental fuel consumption and transfers.
- question_mark
Questions handling of integer vs decimal calculations in mileage.
- question_mark
Tests understanding of threshold-based triggers for additional tank usage.
常见陷阱
外企场景- error
Incorrectly transferring fuel before every 5 liters are spent.
- error
Using decimal division and losing precision in distance calculation.
- error
Not stopping simulation when both tanks are empty.
进阶变体
外企场景- arrow_right_alt
Change the mileage rate to a non-integer value and test integer-only simulation.
- arrow_right_alt
Allow multiple additional tanks and require sequential transfers.
- arrow_right_alt
Adjust the transfer rate to more than 1 liter and verify correct distance computation.