Leetcode 384. Shuffle an Array
You are given an integer array nums
. You need to implement two functions:
shuffle()
: Returns a random shuffling of the array.reset()
: Resets the array to its original configuration and returns it.Implement the class Solution
:
Solution(int[] nums)
: Initializes the object with the integer array nums.int[] reset()
: Resets the array to its original configuration and returns it.int[] shuffle()
: Returns a random shuffling of the array.Input
["Solution", "shuffle", "reset", "shuffle"]
[[[1, 2, 3]], [], [], []]
Output
[null, [3, 1, 2], [1, 2, 3], [1, 3, 2]]
Explanation
Solution solution = new Solution([1, 2, 3]);
solution.shuffle(); // Shuffle the array [1, 2, 3] and return its result.
// Any permutation of [1, 2, 3] must be equally likely to be returned.
solution.reset(); // Resets the array back to its original configuration [1, 2, 3]. Return [1, 2, 3]
solution.shuffle(); // Returns the random shuffling of array [1, 2, 3].
reset()
method to use.The Fisher-Yates algorithm ensures O(n) time complexity for shuffling in a straightforward manner.
Here is the implementation in Java:
import java.util.Random;
public class Solution {
private int[] original;
private int[] array;
private Random rand;
public Solution(int[] nums) {
original = nums.clone();
array = nums.clone();
rand = new Random();
}
public int[] reset() {
array = original.clone();
return array;
}
public int[] shuffle() {
for (int i = array.length - 1; i > 0; i--) {
int j = rand.nextInt(i + 1);
swap(array, i, j);
}
return array;
}
private void swap(int[] array, int i, int j) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
The space complexity is O(n) due to storage of the additional copies of the array.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?