Leetcode 384. Shuffle an Array
You need to design a class to shuffle a given array and also be able to reset it to its original configuration. Imagine this functionality as two operations: “shuffle” and “reset”.
Implement the Solution
class:
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.Before jumping into the solution, it’s important to clarify the requirements:
std::random_shuffle
.Here’s how you can implement this in C++:
#include <vector>
#include <algorithm> // for std::swap
#include <random> // for std::default_random_engine
#include <ctime> // for std::time
class Solution {
private:
std::vector<int> original;
std::vector<int> array;
public:
Solution(std::vector<int>& nums) : original(nums), array(nums) {
// Seed the random number generator
std::srand(unsigned(std::time(0)));
}
std::vector<int> reset() {
array = original;
return array;
}
std::vector<int> shuffle() {
int n = array.size();
// Fisher-Yates Shuffle Algorithm
for (int i = n - 1; i > 0; --i) {
int j = std::rand() % (i + 1);
std::swap(array[i], array[j]);
}
return array;
}
};
Solution(std::vector<int>& nums)
):
reset()
):
shuffle()
):
Both operations reset
and shuffle
are efficient:
Thus, the overall performance is optimal for the given operations.
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?