Leetcode 950. Reveal Cards In Increasing Order

Question

Solution1

考虑先将原序列逆序排列。例子:[19, 17, 13, 11, 10, 8, 7, 5, 3, 2]。新序列为new,依次将第一个元素添加到其中。

1: [19]

2: [17, 19]

3: [13, 17, 19] 但是这时候发现不对了,因为将13移除后,序列变为[19, 17]。因此考虑将19放入第二个位置。

3: [13, 19, 17]

4: [11, 13, 19, 17]。同样,去掉11后,[19, 17, 13]。考虑将17放入第二个位置。

4: [11, 17, 13, 19]

通过上述分析,我们可以得出,依次将新元素放入首尾,将序列new的最后元素置于第二个位置,new剩余部分加入到末位。

1
2
3
4
5
6
class Solution:
def deckRevealedIncreasing(self, deck: List[int]) -> List[int]:
new = []
for elem in sorted(deck)[::-1]:
new = [elem] + new[-1:] + new[:-1]
return new

Solution2

首先对一个index = len(deck), 这个是牌的排序。按照规则对index进行翻牌,得到翻出牌的index,然后将它和按照顺序排列的deck进行zip组合。然后对index进行排序,即得到了所要的序列。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution:
def gen_deck(self, deck):
d = deck.copy()
reveal = True
while d:
if reveal:
yield d.pop(0)
reveal = False
else:
d.append(d.pop(0))
reveal = True
def deckRevealedIncreasing(self, deck: List[int]) -> List[int]:
n = len(deck)
index = self.gen_deck(list(range(n)))
return [n for i, n in sorted(zip(index, sorted(deck)))]