-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInsertDeleteGetRandomO-1.cpp
More file actions
51 lines (40 loc) · 980 Bytes
/
InsertDeleteGetRandomO-1.cpp
File metadata and controls
51 lines (40 loc) · 980 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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
class RandomizedSet {
private:
int size;
unordered_map<int, int> hm;
vector<int> num;
public:
RandomizedSet() {
size = 0;
}
bool insert(int val) {
if (hm.find(val) != hm.end()){
return false;
}
hm.insert({val, size++});
num.push_back(val);
return true;
}
bool remove(int val) {
if(hm.find(val) == hm.end()){
return false;
}
// change 1. vector position, 2. hashm index
num[hm[val]] = num[size - 1];
hm[num[size - 1]] = hm[val];
num.pop_back();
hm.erase(val);
size--;
return true;
}
int getRandom() {
return num[rand()%size];
}
};
/**
* Your RandomizedSet object will be instantiated and called as such:
* RandomizedSet* obj = new RandomizedSet();
* bool param_1 = obj->insert(val);
* bool param_2 = obj->remove(val);
* int param_3 = obj->getRandom();
*/