LeetCode 题解工作台

最小数字游戏

你有一个下标从 0 开始、长度为 偶数 的整数数组 nums ,同时还有一个空数组 arr 。Alice 和 Bob 决定玩一个游戏,游戏中每一轮 Alice 和 Bob 都会各自执行一次操作。游戏规则如下: 每一轮,Alice 先从 nums 中移除一个 最小 元素,然后 Bob 执行同样的操作。…

category

4

题型

code_blocks

6

代码语言

hub

3

相关题

当前训练重点

简单 · 数组·排序

bolt

答案摘要

我们可以将数组 中的元素依次放入一个小根堆中,每次从小根堆中取出两个元素 和 ,然后依次将 和 放入答案数组中,直到小根堆为空。 时间复杂度 $O(n \times \log n)$,空间复杂度 。其中 为数组 的长度。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数组·排序 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

你有一个下标从 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 <= 100
  • 1 <= nums[i] <= 100
  • nums.length % 2 == 0
lightbulb

解题思路

方法一:模拟 + 优先队列(小根堆)

我们可以将数组 nums\textit{nums} 中的元素依次放入一个小根堆中,每次从小根堆中取出两个元素 aabb,然后依次将 bbaa 放入答案数组中,直到小根堆为空。

时间复杂度 O(n×logn)O(n \times \log n),空间复杂度 O(n)O(n)。其中 nn 为数组 nums\textit{nums} 的长度。

1
2
3
4
5
6
7
8
9
10
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
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • 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.

warning

常见陷阱

外企场景
  • 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.

swap_horiz

进阶变体

外企场景
  • 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.

help

常见问题

外企场景

最小数字游戏题解:数组·排序 | LeetCode #2974 简单