384. Shuffle an Array (Medium)
https://leetcode.com/problems/shuffle-an-array/
Shuffle a set of numbers without duplicates.
Example:
// Init an array with set 1, 2, and 3. int[] nums = {1,2,3}; Solution solution = new Solution(nums); // Shuffle the array [1,2,3] and return its result. Any permutation of [1,2,3] must equally likely to be returned. solution.shuffle(); // Resets the array back to its original configuration [1,2,3]. solution.reset(); // Returns the random shuffling of array [1,2,3]. solution.shuffle();
Solutions
class Solution {
int[] nums;
int[] numsCopy;
public Solution(int[] nums) {
this.nums = nums;
numsCopy = new int[nums.length];
reset();
}
public int[] reset() {
System.arraycopy(nums, 0, numsCopy, 0, nums.length);
return nums;
}
private void swap(int[] nums, int x, int y) {
int tmp = nums[x];
nums[x] = nums[y];
nums[y] = tmp;
}
public int[] shuffle() {
for (int i = numsCopy.length - 1; i >= 0; i--) {
int randIdx = (int) (Math.random() * (i + 1));
swap(numsCopy, randIdx, i);
}
return numsCopy;
}
}