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.
实现:
public int[] deckRevealedIncreasing(int[] deck){
int n = deck.length;
Arrays.sort(deck);
Queue<Integer> q = new LinkedList<>();
for(int i = 0; i <n; i++)
q.add(i);
int[] res = new int[n];
for(int i = 0; i<n;i++){
res[q.poll()]=deck[i];
q.add(q.poll());
}
return res;
}
思路:
对deck排序,再创建一个队列插入0-n位数字。迭代求res数组,第一位res[0] = deck[0],第二位res[1]挪到队列最后,此为一次循环,第三位res[2] = deck[2],第四位res[3]挪到队列最后,以此类推。