forked from AnasImloul/Leetcode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathInsert Delete GetRandom O(1) - Duplicates allowed.cpp
69 lines (40 loc) · 1.41 KB
/
Insert Delete GetRandom O(1) - Duplicates allowed.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
62
63
64
65
66
67
68
class RandomizedCollection {
public:
unordered_map<int, unordered_set<int>> mp;
vector<int> arr;
RandomizedCollection() {
}
bool insert(int val) {
arr.push_back(val);
mp[val].insert(arr.size() - 1);
return mp[val].size() == 1;
}
bool remove(int val) {
if(mp.count(val))
{
// pick one occurance of val and delete it
// find the index
int idx = *(mp[val].begin());
// erase from set
mp[val].erase(mp[val].begin());
// replace this index with last element
int last_val = arr.back();
arr[idx] = last_val;
mp[last_val].insert(idx);
mp[last_val].erase(arr.size() - 1);
arr.pop_back();
// if there is no occurance of val is present then erase it from map
if(mp[val].size() == 0)
{
mp.erase(val);
}
return true;
}
return false;
}
int getRandom() {
// generate the random index
int rand_idx = rand() % arr.size();
return arr[rand_idx];
}
};