LeetCode Solutions
384. Shuffle an Array
Time: $O(n)$ Space: $O(n)$
class Solution {
public:
Solution(vector<int>& nums) : nums(move(nums)) {}
/** Resets the array to its original configuration and return it. */
vector<int> reset() {
return nums;
}
/** Returns a random shuffling of the array. */
vector<int> shuffle() {
vector<int> A(nums);
for (int i = A.size() - 1; i > 0; --i) {
const int j = rand() % (i + 1);
swap(A[i], A[j]);
}
return A;
}
private:
vector<int> nums;
};
class Solution {
public Solution(int[] nums) {
this.nums = nums;
}
/** Resets the array to its original configuration and return it. */
public int[] reset() {
return nums;
}
/** Returns a random shuffling of the array. */
public int[] shuffle() {
int[] A = nums.clone();
for (int i = A.length - 1; i > 0; --i) {
final int j = rand.nextInt(i + 1);
swap(A, i, j);
}
return A;
}
private int[] nums;
private Random rand = new Random();
private void swap(int[] A, int i, int j) {
final int temp = A[i];
A[i] = A[j];
A[j] = temp;
}
}
class Solution:
def __init__(self, nums: List[int]):
self.nums = nums
def reset(self) -> List[int]:
"""
Resets the array to its original configuration and return it.
"""
return self.nums
def shuffle(self) -> List[int]:
"""
Returns a random shuffling of the array.
"""
A = self.nums.copy()
for i in range(len(A) - 1, 0, -1):
j = randint(0, i)
A[i], A[j] = A[j], A[i]
return A