forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.cpp
42 lines (37 loc) · 827 Bytes
/
Solution.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
class RandomizedSet {
public:
RandomizedSet() {
}
bool insert(int val) {
if (d.count(val)) {
return false;
}
d[val] = q.size();
q.push_back(val);
return true;
}
bool remove(int val) {
if (!d.count(val)) {
return false;
}
int i = d[val];
d[q.back()] = i;
q[i] = q.back();
q.pop_back();
d.erase(val);
return true;
}
int getRandom() {
return q[rand() % q.size()];
}
private:
unordered_map<int, int> d;
vector<int> q;
};
/**
* 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();
*/