-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathLC0381.cpp
executable file
·61 lines (52 loc) · 1.29 KB
/
LC0381.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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
/*
Problem Statement: https://leetcode.com/problems/insert-delete-getrandom-o1-duplicates-allowed/
Space: O(n)
Author: Mohammed Shoaib, github.com/Mohammed-Shoaib
|------------------------|------|-------|
| Operations | Time | Space |
|------------------------|------|-------|
| RandomizedCollection() | O(1) | O(1) |
| insert(val) | O(1) | O(1) |
| remove(val) | O(1) | O(1) |
| getRandom() | O(1) | O(1) |
|------------------------|------|-------|
*/
class RandomizedCollection {
private:
mt19937 gen;
vector<int> v;
unordered_map<int, unordered_set<int>> m;
public:
RandomizedCollection() : gen(random_device{}()) {}
bool insert(int val) {
bool exist = m.count(val);
m[val].insert(v.size());
v.push_back(val);
return !exist;
}
bool remove(int val) {
if (!m.count(val))
return false;
int pos, ele;
// assign last element to gap
auto it = m[val].begin();
pos = *it;
ele = v.back();
v[pos] = ele;
// remove element
m[val].erase(it);
v.pop_back();
if (!m[ele].empty()) {
m[ele].erase(v.size());
m[ele].insert(pos);
}
// delete value if empty
if (m[val].empty())
m.erase(val);
return true;
}
int getRandom() {
int pos = uniform_int_distribution<int>{0, (int) v.size() - 1}(gen);
return v[pos];
}
};