LeetCode 题解工作台
按递增顺序显示卡牌
牌组中的每张卡牌都对应有一个唯一的整数。你可以按你想要的顺序对这套卡片进行排序。 最初,这些卡牌在牌组里是正面朝下的(即,未显示状态)。 现在,重复执行以下步骤,直到显示所有卡牌为止: 从牌组顶部抽一张牌,显示它,然后将其从牌组中移出。 如果牌组中仍有牌,则将下一张处于牌组顶部的牌放在牌组的底部。 …
4
题型
4
代码语言
3
相关题
当前训练重点
中等 · 队列·driven·状态·processing
答案摘要
根据题目描述,我们知道,数组 `deck` 逆序排列后的序列就是最终的结果。我们可以从最终结果入手,逆向推导出卡片顺序。 遍历逆序排列后的数组 `deck`,先判断队列是否为空,若不为空,则将队尾元素移动到队首,然后将当前元素入队(题目中的逆过程)。若为空,则直接将当前元素入队。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 队列·driven·状态·processing 题型思路
题目描述
牌组中的每张卡牌都对应有一个唯一的整数。你可以按你想要的顺序对这套卡片进行排序。
最初,这些卡牌在牌组里是正面朝下的(即,未显示状态)。
现在,重复执行以下步骤,直到显示所有卡牌为止:
- 从牌组顶部抽一张牌,显示它,然后将其从牌组中移出。
- 如果牌组中仍有牌,则将下一张处于牌组顶部的牌放在牌组的底部。
- 如果仍有未显示的牌,那么返回步骤 1。否则,停止行动。
返回能以递增顺序显示卡牌的牌组顺序。
答案中的第一张牌被认为处于牌堆顶部。
示例:
输入:[17,13,11,2,3,5,7] 输出:[2,13,3,11,5,17,7] 解释: 我们得到的牌组顺序为 [17,13,11,2,3,5,7](这个顺序不重要),然后将其重新排序。 重新排序后,牌组以 [2,13,3,11,5,17,7] 开始,其中 2 位于牌组的顶部。 我们显示 2,然后将 13 移到底部。牌组现在是 [3,11,5,17,7,13]。 我们显示 3,并将 11 移到底部。牌组现在是 [5,17,7,13,11]。 我们显示 5,然后将 17 移到底部。牌组现在是 [7,13,11,17]。 我们显示 7,并将 13 移到底部。牌组现在是 [11,17,13]。 我们显示 11,然后将 17 移到底部。牌组现在是 [13,17]。 我们展示 13,然后将 17 移到底部。牌组现在是 [17]。 我们显示 17。 由于所有卡片都是按递增顺序排列显示的,所以答案是正确的。
提示:
1 <= A.length <= 10001 <= A[i] <= 10^6- 对于所有的
i != j,A[i] != A[j]
解题思路
方法一:队列模拟
根据题目描述,我们知道,数组 deck 逆序排列后的序列就是最终的结果。我们可以从最终结果入手,逆向推导出卡片顺序。
遍历逆序排列后的数组 deck,先判断队列是否为空,若不为空,则将队尾元素移动到队首,然后将当前元素入队(题目中的逆过程)。若为空,则直接将当前元素入队。
最后,将队列中的元素依次出队,即可得到最终的结果。
时间复杂度 ,空间复杂度 。其中 为数组 deck 的长度。
class Solution:
def deckRevealedIncreasing(self, deck: List[int]) -> List[int]:
q = deque()
for v in sorted(deck, reverse=True):
if q:
q.appendleft(q.pop())
q.appendleft(v)
return list(q)
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | O(n \log n) |
| 空间 | O(n) |
面试官常问的追问
外企场景- question_mark
Candidates who sort first and then simulate backwards show understanding of queue-driven state manipulation.
- question_mark
Watch for explicit handling of the 'move top card to bottom' step; missing it often causes wrong sequences.
- question_mark
Candidates may ask about stability or whether duplicates exist; this signals attention to constraints and uniqueness.
常见陷阱
外企场景- error
Failing to simulate the reveal process in reverse order, leading to incorrect initial deck sequences.
- error
Ignoring the move-to-bottom step when constructing the initial deck order, producing non-increasing reveals.
- error
Attempting to place cards greedily without a queue, which often breaks the intended reveal pattern for larger decks.
进阶变体
外企场景- arrow_right_alt
Reveal cards in decreasing order using a similar queue-driven approach but starting from the largest card.
- arrow_right_alt
Allow duplicate cards in the deck, requiring additional tracking to maintain correct relative positions.
- arrow_right_alt
Simulate a double-move variant where the top two cards are moved instead of one, increasing queue complexity.