Link: https://leetcode.com/problems/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 all i != j
題目翻譯:
在一副牌中,每張牌都有一個唯一的整數。您可以按照任何排序套牌。
最初,所有牌都在一個牌組中面朝下(未揭曉)。
現在,你反复執行以下步驟,直到所有牌都顯示出來:
- 拿到牌組的頂牌,揭開它,然後把它從牌組中拿出來。
- 如果牌組中仍有牌,則將牌組的下一張頂牌放在牌組底部。
- 如果仍有未顯示的卡,請返回步驟 1.否則,停止。
返回甲板的訂單,以便按遞增順序顯示卡片。
答案中的第一個條目被認為是套牌的頂部。
程式思路:
用容器 deque 做會比用 vector 稍微方便點。題目的意思就是說 你的 input 是上述動作所產生出來的”結果”,所以叫你把”原本”的排組個 output 出來,所以我們要把它做過的步驟反著做。而且要記得先把 input 做個遞減排列。
class Solution {
public:
vector<int> deckRevealedIncreasing(vector<int>& deck) {
deque <int> deck_que;
//sort deck decreasing
sort(deck.begin(),deck.end(),[](int a,int b){return a > b;});
for(auto val : deck)
{
if(!deck_que.empty())
{
deck_que.push_front(deck_que.back());
deck_que.pop_back();
}
deck_que.push_front(val);
}
return vector (deck_que.begin(),deck_que.end());
}
};