LeetCode 题解工作台
消除游戏
列表 arr 由在范围 [1, n] 中的所有整数组成,并按严格递增排序。请你对 arr 应用下述算法: 从左到右,删除第一个数字,然后每隔一个数字删除一个,直到到达列表末尾。 重复上面的步骤,但这次是从右到左。也就是,删除最右侧的数字,然后剩下的数字每隔一个删除一个。 不断重复这两步,从左到右和从…
2
题型
4
代码语言
3
相关题
当前训练重点
中等 · 数学·递归
答案摘要
class Solution: def lastRemaining(self, n: int) -> int:
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数学·递归 题型思路
题目描述
列表 arr 由在范围 [1, n] 中的所有整数组成,并按严格递增排序。请你对 arr 应用下述算法:
- 从左到右,删除第一个数字,然后每隔一个数字删除一个,直到到达列表末尾。
- 重复上面的步骤,但这次是从右到左。也就是,删除最右侧的数字,然后剩下的数字每隔一个删除一个。
- 不断重复这两步,从左到右和从右到左交替进行,直到只剩下一个数字。
给你整数 n ,返回 arr 最后剩下的数字。
示例 1:
输入:n = 9 输出:6 解释: arr = [1, 2, 3, 4, 5, 6, 7, 8, 9] arr = [2, 4, 6, 8] arr = [2, 6] arr = [6]
示例 2:
输入:n = 1 输出:1
提示:
1 <= n <= 109
解题思路
方法一
class Solution:
def lastRemaining(self, n: int) -> int:
a1, an = 1, n
i, step, cnt = 0, 1, n
while cnt > 1:
if i % 2:
an -= step
if cnt % 2:
a1 += step
else:
a1 += step
if cnt % 2:
an -= step
cnt >>= 1
step <<= 1
i += 1
return a1
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(log n) because each round halves the number of elements. Space complexity is O(log n) due to recursion stack, with no full array simulation needed. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Candidate tries simulating the array fully instead of recognizing elimination patterns.
- question_mark
Candidate identifies the left-right elimination pattern and updates first element systematically.
- question_mark
Candidate applies recursion with step tracking to reach the final number efficiently.
常见陷阱
外企场景- error
Simulating the full array leads to TLE for large n.
- error
Forgetting that the first element moves differently when eliminating from right with odd count.
- error
Confusing step updates between rounds and miscalculating the first remaining number.
进阶变体
外企场景- arrow_right_alt
Modify elimination to remove every k-th element instead of every other, requiring adjustment to step computation.
- arrow_right_alt
Start elimination from right first, which changes the first element update logic slightly.
- arrow_right_alt
Return the sequence of remaining numbers after each round instead of just the last number.