LeetCode 题解工作台
最小数字游戏
你有一个下标从 0 开始、长度为 偶数 的整数数组 nums ,同时还有一个空数组 arr 。Alice 和 Bob 决定玩一个游戏,游戏中每一轮 Alice 和 Bob 都会各自执行一次操作。游戏规则如下: 每一轮,Alice 先从 nums 中移除一个 最小 元素,然后 Bob 执行同样的操作。…
4
题型
6
代码语言
3
相关题
当前训练重点
简单 · 数组·排序
答案摘要
我们可以将数组 中的元素依次放入一个小根堆中,每次从小根堆中取出两个元素 和 ,然后依次将 和 放入答案数组中,直到小根堆为空。 时间复杂度 $O(n \times \log n)$,空间复杂度 。其中 为数组 的长度。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·排序 题型思路
题目描述
你有一个下标从 0 开始、长度为 偶数 的整数数组 nums ,同时还有一个空数组 arr 。Alice 和 Bob 决定玩一个游戏,游戏中每一轮 Alice 和 Bob 都会各自执行一次操作。游戏规则如下:
- 每一轮,Alice 先从
nums中移除一个 最小 元素,然后 Bob 执行同样的操作。 - 接着,Bob 会将移除的元素添加到数组
arr中,然后 Alice 也执行同样的操作。 - 游戏持续进行,直到
nums变为空。
返回结果数组 arr 。
示例 1:
输入:nums = [5,4,2,3] 输出:[3,2,5,4] 解释:第一轮,Alice 先移除 2 ,然后 Bob 移除 3 。然后 Bob 先将 3 添加到 arr 中,接着 Alice 再将 2 添加到 arr 中。于是 arr = [3,2] 。 第二轮开始时,nums = [5,4] 。Alice 先移除 4 ,然后 Bob 移除 5 。接着他们都将元素添加到 arr 中,arr 变为 [3,2,5,4] 。
示例 2:
输入:nums = [2,5] 输出:[5,2] 解释:第一轮,Alice 先移除 2 ,然后 Bob 移除 5 。然后 Bob 先将 5 添加到 arr 中,接着 Alice 再将 2 添加到 arr 中。于是 arr = [5,2] 。
提示:
1 <= nums.length <= 1001 <= nums[i] <= 100nums.length % 2 == 0
解题思路
方法一:模拟 + 优先队列(小根堆)
我们可以将数组 中的元素依次放入一个小根堆中,每次从小根堆中取出两个元素 和 ,然后依次将 和 放入答案数组中,直到小根堆为空。
时间复杂度 ,空间复杂度 。其中 为数组 的长度。
class Solution:
def numberGame(self, nums: List[int]) -> List[int]:
heapify(nums)
ans = []
while nums:
a, b = heappop(nums), heappop(nums)
ans.append(b)
ans.append(a)
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Ensure the candidate uses sorting as a first step to solve the problem.
- question_mark
Look for the candidate's understanding of simulation and alternating turns.
- question_mark
Check if the candidate can optimize using heaps or priority queues.
常见陷阱
外企场景- error
Forgetting to sort the array before simulating the game, which leads to incorrect answers.
- error
Improper simulation of the turns, such as not appending the elements in the correct order.
- error
Not using efficient data structures like heaps, resulting in higher time complexity.
进阶变体
外企场景- arrow_right_alt
Modify the problem to have Alice and Bob pick elements based on a different rule, such as alternating picks instead of smallest-first.
- arrow_right_alt
Change the number of players and adjust the game mechanics accordingly.
- arrow_right_alt
Introduce a condition where players can pick from a specific range of numbers rather than from the entire sorted array.