950. Reveal Cards In Increasing Order

https://leetcode.com/problems/reveal-cards-in-increasing-order/

这题目还蛮有意思的,解决方法是逆向推导。先观察例子,然后总结出一般规律。

假设目标序列是 1,2,3,4,5,6,7. 从尾部开始考虑

假设我们现在要取x, 之后序列是S的话,那么要求序列就是 x + S[-1] + S[:-1].

class Solution:
    def deckRevealedIncreasing(self, deck: List[int]) -> List[int]:
        from collections import deque
        dq = deque()

        deck = sorted(deck)
        n = len(deck)

        dq.append(deck[-1])
        for i in reversed(range(n - 1)):
            v = deck[i]
            x = dq.pop()
            dq.appendleft(x)
            dq.appendleft(v)

        ans = list(dq)
        return ans