Skip to content

Commit c308273

Browse files
committed
Time: 751 ms (7.32%), Space: 97.1 MB (19.16%) - LeetHub
1 parent 6a527fb commit c308273

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
class RandomizedSet {
2+
public:
3+
unordered_map<int,int>mp;
4+
vector<int>arr;
5+
6+
RandomizedSet() {
7+
8+
}
9+
10+
bool insert(int val) {
11+
if(mp.count(val)){
12+
return false;
13+
}
14+
else{
15+
arr.push_back(val);
16+
mp[val] = arr.size()-1;
17+
}
18+
return true;
19+
}
20+
21+
bool remove(int val) {
22+
if(mp.count(val)){
23+
int idx = mp[val];
24+
int last = arr.back();
25+
arr[idx] = last;
26+
arr.pop_back();
27+
mp[last] = idx;
28+
mp.erase(val);
29+
return true;
30+
}
31+
return false;
32+
33+
}
34+
35+
int getRandom() {
36+
37+
return arr[rand()%arr.size()];
38+
}
39+
};
40+
41+
/**
42+
* Your RandomizedSet object will be instantiated and called as such:
43+
* RandomizedSet* obj = new RandomizedSet();
44+
* bool param_1 = obj->insert(val);
45+
* bool param_2 = obj->remove(val);
46+
* int param_3 = obj->getRandom();
47+
*/

0 commit comments

Comments
 (0)