LeetCode 题解工作台
极大极小游戏
给你一个下标从 0 开始的整数数组 nums ,其长度是 2 的幂。 对 nums 执行下述算法: 设 n 等于 nums 的长度,如果 n == 1 , 终止 算法过程。否则, 创建 一个新的整数数组 newNums ,新数组长度为 n / 2 ,下标从 0 开始。 对于满足 0 的每个 偶数 下…
2
题型
7
代码语言
3
相关题
当前训练重点
简单 · 数组·模拟
答案摘要
根据题意,我们可以模拟整个过程,最后剩下的数字即为答案。在实现上,我们不需要额外创建数组,直接在原数组上进行操作即可。 时间复杂度 ,其中 是数组 的长度。空间复杂度 。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·模拟 题型思路
题目描述
给你一个下标从 0 开始的整数数组 nums ,其长度是 2 的幂。
对 nums 执行下述算法:
- 设
n等于nums的长度,如果n == 1,终止 算法过程。否则,创建 一个新的整数数组newNums,新数组长度为n / 2,下标从 0 开始。 - 对于满足
0 <= i < n / 2的每个 偶数 下标i,将newNums[i]赋值 为min(nums[2 * i], nums[2 * i + 1])。 - 对于满足
0 <= i < n / 2的每个 奇数 下标i,将newNums[i]赋值 为max(nums[2 * i], nums[2 * i + 1])。 - 用
newNums替换nums。 - 从步骤 1 开始 重复 整个过程。
执行算法后,返回 nums 中剩下的那个数字。
示例 1:

输入:nums = [1,3,5,2,4,8,2,2] 输出:1 解释:重复执行算法会得到下述数组。 第一轮:nums = [1,5,4,2] 第二轮:nums = [1,4] 第三轮:nums = [1] 1 是最后剩下的那个数字,返回 1 。
示例 2:
输入:nums = [3] 输出:3 解释:3 就是最后剩下的数字,返回 3 。
提示:
1 <= nums.length <= 10241 <= nums[i] <= 109nums.length是2的幂
解题思路
方法一:模拟
根据题意,我们可以模拟整个过程,最后剩下的数字即为答案。在实现上,我们不需要额外创建数组,直接在原数组上进行操作即可。
时间复杂度 ,其中 是数组 的长度。空间复杂度 。
class Solution:
def minMaxGame(self, nums: List[int]) -> int:
n = len(nums)
while n > 1:
n >>= 1
for i in range(n):
a, b = nums[i << 1], nums[i << 1 | 1]
nums[i] = min(a, b) if i % 2 == 0 else max(a, b)
return nums[0]
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
The candidate correctly simulates the process without overcomplicating the solution.
- question_mark
The candidate handles edge cases and large inputs efficiently.
- question_mark
The candidate explains how the time complexity is reduced with each step of the iteration.
常见陷阱
外企场景- error
Misunderstanding the problem and applying the wrong operation for even and odd indices.
- error
Not recognizing that the length of the array is halved at each step, which can lead to inefficient solutions.
- error
Failing to handle edge cases such as when the array has only one element or when all elements are equal.
进阶变体
外企场景- arrow_right_alt
Simulate with different operations (min vs max), alternating by indices or positions.
- arrow_right_alt
Modify the problem to find the minimum/maximum value of the remaining number, instead of just the last one.
- arrow_right_alt
Apply the same process but with different array lengths (not restricted to power of 2).