-
Notifications
You must be signed in to change notification settings - Fork 28
/
Insert_Delete_GetRandom_O(1)-Duplicates_allowed.cpp
60 lines (52 loc) · 1.78 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
class RandomizedCollection {
unordered_map<int, set<int> > indices;
vector<int> values;
public:
/** Initialize your data structure here. */
RandomizedCollection() {
indices = unordered_map<int, set<int> >();
values = vector<int>();
srand(time(NULL));
}
/** Inserts a value to the collection. Returns true if the collection did not already contain the specified element. */
bool insert(int val) {
if(!indices.count(val)) { // indices.find(val) == indices.end() won't work
indices[val] = set<int>();
}
indices[val].insert(values.size());
values.push_back(val);
return ret;
}
/** Removes a value from the collection. Returns true if the collection contained the specified element. */
bool remove(int val) {
if(!indices.count(val)) {
return false;
}
set<int> pos = indices[val];
int indx = *pos.begin();
int lastPos = values.size() - 1;
int lastVal = values[lastPos];
swap(values[indx], values[lastPos]);
values.pop_back();
indices[val].erase(indx);
if(indices[val].size() == 0) {
indices.erase(val);
}
if(indices.count(lastVal)) {
indices[lastVal].erase(lastPos);
indices[lastVal].insert(indx);
}
return true;
}
/** Get a random element from the collection. */
int getRandom() {
return values[rand() % (int)values.size()];
}
};
/**
* Your RandomizedCollection object will be instantiated and called as such:
* RandomizedCollection obj = new RandomizedCollection();
* bool param_1 = obj.insert(val);
* bool param_2 = obj.remove(val);
* int param_3 = obj.getRandom();
*/