LeetCode 题解工作台
消灭怪物的最大数量
你正在玩一款电子游戏,在游戏中你需要保护城市免受怪物侵袭。给定一个 下标从 0 开始 且大小为 n 的整数数组 dist ,其中 dist[i] 是第 i 个怪物与城市的 初始距离 (单位:千米)。 怪物以 恒定 的速度走向城市。每个怪物的速度都以一个长度为 n 的整数数组 speed 表示,其中 …
3
题型
7
代码语言
3
相关题
当前训练重点
中等 · 贪心·invariant
答案摘要
我们用 数组记录每个怪物最晚可被消灭的时间。对于第 个怪物,最晚可被消灭的时间满足: $$\textit{times}[i] = \left\lfloor \frac{\textit{dist}[i]-1}{\textit{speed}[i]} \right\rfloor$$
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 贪心·invariant 题型思路
题目描述
你正在玩一款电子游戏,在游戏中你需要保护城市免受怪物侵袭。给定一个 下标从 0 开始 且大小为 n 的整数数组 dist ,其中 dist[i] 是第 i 个怪物与城市的 初始距离(单位:千米)。
怪物以 恒定 的速度走向城市。每个怪物的速度都以一个长度为 n 的整数数组 speed 表示,其中 speed[i] 是第 i 个怪物的速度(单位:千米/分)。
你有一种武器,一旦充满电,就可以消灭 一个 怪物。但是,武器需要 一分钟 才能充电。武器在游戏开始时是充满电的状态,怪物从 第 0 分钟 时开始移动。
一旦任一怪物到达城市,你就输掉了这场游戏。如果某个怪物 恰好 在某一分钟开始时到达城市(距离表示为0),这也会被视为 输掉 游戏,在你可以使用武器之前,游戏就会结束。
返回在你输掉游戏前可以消灭的怪物的 最大 数量。如果你可以在所有怪物到达城市前将它们全部消灭,返回 n 。
示例 1:
输入:dist = [1,3,4], speed = [1,1,1] 输出:3 解释: 第 0 分钟开始时,怪物的距离是 [1,3,4],你消灭了第一个怪物。 第 1 分钟开始时,怪物的距离是 [X,2,3],你消灭了第二个怪物。 第 3 分钟开始时,怪物的距离是 [X,X,2],你消灭了第三个怪物。 所有 3 个怪物都可以被消灭。
示例 2:
输入:dist = [1,1,2,3], speed = [1,1,1,1] 输出:1 解释: 第 0 分钟开始时,怪物的距离是 [1,1,2,3],你消灭了第一个怪物。 第 1 分钟开始时,怪物的距离是 [X,0,1,2],所以你输掉了游戏。 你只能消灭 1 个怪物。
示例 3:
输入:dist = [3,2,4], speed = [5,3,2] 输出:1 解释: 第 0 分钟开始时,怪物的距离是 [3,2,4],你消灭了第一个怪物。 第 1 分钟开始时,怪物的距离是 [X,0,2],你输掉了游戏。 你只能消灭 1 个怪物。
提示:
n == dist.length == speed.length1 <= n <= 1051 <= dist[i], speed[i] <= 105
解题思路
方法一:排序 + 贪心
我们用 数组记录每个怪物最晚可被消灭的时间。对于第 个怪物,最晚可被消灭的时间满足:
接下来,我们对 数组升序排列。
然后遍历 数组,对于第 个怪物,如果 ,说明第 个怪物可以被消灭,否则说明第 个怪物无法被消灭,直接返回 即可。
若所有怪物都可以被消灭,则返回 。
时间复杂度 ,空间复杂度 。其中 是数组的长度。
class Solution:
def eliminateMaximum(self, dist: List[int], speed: List[int]) -> int:
times = sorted((d - 1) // s for d, s in zip(dist, speed))
for i, t in enumerate(times):
if t < i:
return i
return len(times)
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | O(n \cdot \log{}n) |
| 空间 | O(n) |
面试官常问的追问
外企场景- question_mark
Candidate identifies the greedy strategy and time-based elimination process.
- question_mark
Candidate correctly explains sorting and how the time to reach the city affects the elimination order.
- question_mark
Candidate optimizes the solution with time complexity analysis and justifies the O(n log n) time complexity.
常见陷阱
外企场景- error
Not considering the time it takes for each monster to reach the city and eliminating in the wrong order.
- error
Misunderstanding that the weapon takes time to charge, affecting the timing of eliminations.
- error
Failing to correctly handle edge cases where the monsters are too close to the city when the weapon is ready.
进阶变体
外企场景- arrow_right_alt
What if the weapon charges faster or has a different charging time?
- arrow_right_alt
What if monsters move at different speeds but have the same distance?
- arrow_right_alt
What if there is a limit on how many monsters can be eliminated?