-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathLC0384.cpp
More file actions
executable file
·37 lines (31 loc) · 828 Bytes
/
LC0384.cpp
File metadata and controls
executable file
·37 lines (31 loc) · 828 Bytes
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
37
/*
Problem Statement: https://leetcode.com/problems/shuffle-an-array/
Space: O(n)
Author: Mohammed Shoaib, github.com/Mohammed-Shoaib
|----------------|-------|-------|
| Operations | Time | Space |
|----------------|-------|-------|
| Solution(nums) | O(n) | O(n) |
| reset() | O(n) | O(n) |
| shuffle() | O(n) | O(n) |
|----------------|-------|-------|
*/
class Solution {
private:
mt19937 gen;
vector<int> org, nums;
public:
Solution(vector<int>& nums): org(nums), nums(nums), gen(random_device{}()) {}
vector<int> reset() {
return org;
}
vector<int> shuffle() {
int n = nums.size();
// fisher–yates shuffle, durstenfeld's version
for (int i = 0; i < n; i++) {
int pos = uniform_int_distribution<int>{i, n - 1}(gen);
swap(nums[i], nums[pos]);
}
return nums;
}
};