forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 1
/
shuffle-an-array.cpp
36 lines (29 loc) · 886 Bytes
/
shuffle-an-array.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
// Time: O(n)
// Space: O(n)
class Solution {
public:
Solution(vector<int> nums) : nums_(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> nums{nums_};
default_random_engine seed((random_device())());
for (int i = 0; i < nums.size(); ++i) {
swap(nums[i], nums[uniform_int_distribution<int>{
i, static_cast<int>(nums.size()) - 1}(seed)]);
}
return nums;
}
private:
const vector<int> nums_;
};
/**
* Your Solution object will be instantiated and called as such:
* Solution obj = new Solution(nums);
* vector<int> param_1 = obj.reset();
* vector<int> param_2 = obj.shuffle();
*/