[LeetCode] 950. Reveal Cards In Increasing Order 按递增顺序显示卡牌
In a deck of cards, every card has a unique integer. You can order the deck in any order you want.
Initially, all the cards start face down (unrevealed) in one deck.
Now, you do the following steps repeatedly, until all cards are revealed:
- Take the top card of the deck, reveal it, and take it out of the deck.
- If there are still cards in the deck, put the next top card of the deck at the bottom of the deck.
- If there are still unrevealed cards, go back to step 1. Otherwise, stop.
Return an ordering of the deck that would reveal the cards in increasing order.
The first entry in the answer is considered to be the top of the deck.
Example 1:
Input: [17,13,11,2,3,5,7]
Output: [2,13,3,11,5,17,7]
Explanation:
We get the deck in the order [17,13,11,2,3,5,7] (this order doesn't matter), and reorder it.
After reordering, the deck starts as [2,13,3,11,5,17,7], where 2 is the top of the deck.
We reveal 2, and move 13 to the bottom. The deck is now [3,11,5,17,7,13].
We reveal 3, and move 11 to the bottom. The deck is now [5,17,7,13,11].
We reveal 5, and move 17 to the bottom. The deck is now [7,13,11,17].
We reveal 7, and move 13 to the bottom. The deck is now [11,17,13].
We reveal 11, and move 17 to the bottom. The deck is now [13,17].
We reveal 13, and move 17 to the bottom. The deck is now [17].
We reveal 17.
Since all the cards revealed are in increasing order, the answer is correct.
Note:
1 <= A.length <= 1000
1 <= A[i] <= 10^6
A[i] != A[j]
for alli != j
这道题给了我们一些卡牌,让返回一种顺序,使得按照某种发牌规则可以发出从小到大的牌,发牌是翻开一张牌,然后把下一张牌移到末尾,然后再翻下一张牌,再移动下一张牌到末尾,以此类推,直至所有的牌都翻开。题目中给的例子也很好的说明了这一点,可以观察到偶数 index 上的数字是递增的,因为按照翻一张移一张的顺序,偶数 index 上的数字是要先翻开的,所以一定是有序的,关键在于奇数 index 上的数字是否也有顺序,博主看中间三个数是 13,11,17,以为是中间最小,然后向两边扩展,但是又举了一些例子,尝试了总共有偶数张牌的情况,发现无法找出一个统一的规律,就卡壳了。后来逛论坛发现大家都用的是简单粗暴的方法,根本不用找规律,直接用一个队列 queue 来模拟整个发牌规则即可。首先要给数组排个序,然后建立一个数组,把所有 index 按顺序装入队列,之后就开始遍历,先从队首取出一个 index,此时的 index 是要翻开的,所以将 deck[i] 放入结果 res 中的对应的 index 位置,然后再从队首取下一个 index,这个 index 是要移到末尾的,直接加入队列。这样操作n次之后,整个 res 数组就会被正确的赋值了,参见代码如下:
class Solution {
public:
vector<int> deckRevealedIncreasing(vector<int>& deck) {
int n = deck.size();
vector<int> res(n);
queue<int> q;
sort(deck.begin(), deck.end());
for (int i = 0; i < n; ++i) q.push(i);
for (int i = 0; i < n; ++i) {
int t = q.front(); q.pop();
res[t] = deck[i];
int next = q.front(); q.pop();
q.push(next);
}
return res;
}
};
Github 同步地址:
https://github.com/grandyang/leetcode/issues/950
参考资料:
https://leetcode.com/problems/reveal-cards-in-increasing-order/