2019-03-27 14:10:37
问题描述:
问题求解:
模拟题。考虑角度是从结果来进行反推。
input - [2,3,5,7,11,13,17] (just sort the input that you get)
The last number that you wanna get is the last number in the array - (17)
The penultimate number is 13. So put 13 on top of 17 (13,17) and bring the last number to top (17,13). Now while you perform the action with (17,13), you will place 17 in the bottom and reveal 13 first - so it becomes (17), now reveal 17.
The number that you want before 13 is 11. Place 11 on top now (11,17,13) and bring the last number to the top (13,11,17). Now when you perfom the action with (13,11,17), you will place 13 in the bottom and reveal 11 - so it becomes (17,13), now you will place 17 in the bottom and reveal 13 - it becomes (17), and then you will reveal 17.
current is 7 -> (7,13,11,17) -> (17,7,13,11) (add 7 to the queue, remove 17 from the queue and add back 17 to the queue)
current is 5 -> (5,17,7,13,11) -> (11,5,17,7,13) (add 5 to the queue, remove 11 from the queue and add back 11 to the queue)
current is 3 -> (3,11,5,17,7,13) -> (13,3,11,5,17,7) (add current to the queue, remove from the queue, add the removed number back to the queue)
current is 2 -> (2,13,3,11,5,17,7) -> Stop here since you don't have anymore numbers.
public int[] deckRevealedIncreasing(int[] deck) { int[] res = new int[deck.length]; Arrays.sort(deck); if (deck.length < 3) return deck; Deque<Integer> deque = new LinkedList<>(); for (int i = deck.length - 1; i >= 1; i--) { deque.addFirst(deck[i]); deque.addFirst(deque.pollLast()); } deque.addFirst(deck[0]); for (int i = 0; i < deck.length; i++) res[i] = deque.pollFirst(); return res; }