Skip to content

384. Shuffle an Array

  • Time: $O(n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
 public:
  Solution(vector<int>& nums) : nums(std::move(nums)) {}

  vector<int> reset() {
    return nums;
  }

  vector<int> shuffle() {
    vector<int> arr(nums);
    for (int i = arr.size() - 1; i > 0; --i) {
      const int j = rand() % (i + 1);
      swap(arr[i], arr[j]);
    }
    return arr;
  }

 private:
  vector<int> nums;
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Solution {
  public Solution(int[] nums) {
    this.nums = nums;
  }

  public int[] reset() {
    return nums;
  }

  public int[] shuffle() {
    int[] arr = nums.clone();
    for (int i = arr.length - 1; i > 0; --i) {
      final int j = rand.nextInt(i + 1);
      swap(arr, i, j);
    }
    return arr;
  }

  private int[] nums;
  private Random rand = new Random();

  private void swap(int[] arr, int i, int j) {
    final int temp = arr[i];
    arr[i] = arr[j];
    arr[j] = temp;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Solution:
  def __init__(self, nums: list[int]):
    self.nums = nums

  def reset(self) -> list[int]:
    return self.nums

  def shuffle(self) -> list[int]:
    arr = self.nums.copy()
    for i in range(len(arr) - 1, 0, -1):
      j = random.randint(0, i)
      arr[i], arr[j] = arr[j], arr[i]
    return arr