Skip to content

1470. Shuffle the Array 👍

  • Time: $O(n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class Solution {
 public:
  vector<int> shuffle(vector<int>& nums, int n) {
    vector<int> ans;
    for (int i = 0; i < n; ++i) {
      ans.push_back(nums[i]);
      ans.push_back(nums[i + n]);
    }
    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class Solution {
  public int[] shuffle(int[] nums, int n) {
    int[] ans = new int[2 * n];
    for (int i = 0; i < n; ++i) {
      ans[i * 2] = nums[i];
      ans[i * 2 + 1] = nums[i + n];
    }
    return ans;
  }
}
1
2
3
4
5
6
7
class Solution:
  def shuffle(self, nums: list[int], n: int) -> list[int]:
    ans = []
    for a, b in zip(nums[:n], nums[n:]):
      ans.append(a)
      ans.append(b)
    return ans