-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathInsertDeleteGetRandomwDuplicates.cpp
More file actions
48 lines (43 loc) · 1.45 KB
/
InsertDeleteGetRandomwDuplicates.cpp
File metadata and controls
48 lines (43 loc) · 1.45 KB
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
class RandomizedCollection {
public:
/** Initialize your data structure here. */
vector<int>list;
unordered_map<int,unordered_set<int>>index;
RandomizedCollection() {
}
/** Inserts a value to the collection. Returns true if the collection did not already contain the specified element. */
bool insert(int val) {
list.push_back(val);
index[val].insert(list.size()-1);
if(index[val].size()==1)
return true;
return false;
}
/** Removes a value from the collection. Returns true if the collection contained the specified element. */
bool remove(int val) {
if((index.find(val) == index.end()) || (index[val].size()==0))
return false;
auto it = index[val].begin();
int ind = *it;
index[val].erase(it);
if(index[val].size() == 0)
index.erase(val);
list[ind] = list[list.size()-1];
index[list[ind]].insert(ind);
index[list[ind]].erase(list.size()-1);
list.pop_back();
return true;
}
/** Get a random element from the collection. */
int getRandom() {
//int x = rand()%list.size();
return list[rand()%list.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();
*/