35. Interleave the Halves
A deck of 2n numbered cards has just been cut into two equal piles: the first n cards form the left pile and the last n cards form the right pile. A dealer riffle-shuffles the piles together by taking one card from the left pile, then one from the right pile, then the next from the left, and so on, until both piles are used up.
Write a method interleave that takes the array nums (the left pile followed by the right pile, with 2n cards in total) and the integer n, and returns the deck after the riffle shuffle.
Example 1
- Input:
- nums = [2,5,1,3,4,7], n = 3
- Output:
- [2,3,5,4,1,7]
- Explanation:
The left pile is 2, 5, 1 and the right pile is 3, 4, 7. Alternating them gives 2, 3, 5, 4, 1, 7.
Example 2
- Input:
- nums = [1,2,3,4], n = 2
- Output:
- [1,3,2,4]
- Explanation:
Left pile 1, 2 and right pile 3, 4 interleave into [1, 3, 2, 4].
Constraints
1 ≤ n ≤ 500
nums.length == 2 * n
-109 ≤ nums[i] ≤ 109
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Expected complexity
- Time
- O(n)
- Space
- O(n)