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/