Given an integer array nums
, design an algorithm to randomly shuffle the array. Implement the Solution
class with the following methods:
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.Example:
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 randomly and return the result. Any permutation of [1, 2, 3] must be equally likely to be returned.
solution.reset(); // Resets the array to its original configuration [1, 2, 3]. Return [1, 2, 3]
solution.shuffle(); // Returns the random shuffling of array [1, 2, 3]
__init__
method):
reset
):
shuffle
):
import random
class Solution:
def __init__(self, nums: list[int]):
self.original = nums[:] # store the original array
self.array = nums[:] # create a mutable copy of the array
def reset(self) -> list[int]:
self.array = self.original[:] # reset to original configuration
return self.array
def shuffle(self) -> list[int]:
# Implementing Fisher-Yates shuffle
for i in range(len(self.array)):
swap_idx = random.randint(i, len(self.array) - 1) # select a random index to swap with
self.array[i], self.array[swap_idx] = self.array[swap_idx], self.array[i]
return self.array
__init__
method):
reset
):
shuffle
):
The Fisher-Yates algorithm ensures that each possible permutation of the array is equally likely, fulfilling the requirement for uniform randomness.
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?