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.
这道题的思路是逆向操作,先对deck排序,然后按照相反的操作顺序就可以得出最初的数组
class Solution {
public int[] deckRevealedIncreasing(int[] deck) {
if(deck == null || deck.length <= 1)
return deck;
Arrays.sort(deck);
int[] res = new int[deck.length];
for(int i = deck.length - 1; i >= 0; i--) {
rotate(res, i + 1);
res[i] = deck[i];
}
return res;
}
public void rotate(int[] res, int i) {
if(i >= res.length - 1)
return;
int temp = res[res.length - 1];
for(int j = res.length - 1; j > i; j--) {
res[j] = res[j - 1];
}
res[i] = temp;
}
}