Skip to content

Commit 31f04e5

Browse files
Merge pull request #163 from FazeelUsmani/insert-delete-getRandom-in-O(1)-time-1
Create 21_insertDelRandom.cpp
2 parents 20c89ed + a38e9aa commit 31f04e5

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
class RandomizedSet {
2+
public:
3+
void swap(int &a, int &b){
4+
int temp = b;
5+
b = a;
6+
a = temp;
7+
}
8+
vector<int> A;
9+
unordered_map<int, int> umap;
10+
/** Initialize your data structure here. */
11+
RandomizedSet() {
12+
A.clear();
13+
umap.clear();
14+
}
15+
16+
/** Inserts a value to the set. Returns true if the set did not already contain the specified element. */
17+
bool insert(int val) {
18+
if (umap.find(val) != umap.end())
19+
return false;
20+
A.push_back(val);
21+
umap.insert(pair<int, int>(val, A.size() - 1));
22+
23+
return true;
24+
}
25+
26+
/** Removes a value from the set. Returns true if the set contained the specified element. */
27+
bool remove(int val) {
28+
if (umap.find(val) == umap.end())
29+
return false;
30+
31+
int index = umap[val];
32+
A[index] = A[A.size()-1];
33+
umap[A[index]] = index;
34+
A.pop_back();
35+
umap.erase(val);
36+
37+
return true;
38+
}
39+
40+
/** Get a random element from the set. */
41+
int getRandom() {
42+
return A[rand() % A.size()];
43+
}
44+
};
45+
46+
/**
47+
* Your RandomizedSet object will be instantiated and called as such:
48+
* RandomizedSet* obj = new RandomizedSet();
49+
* bool param_1 = obj->insert(val);
50+
* bool param_2 = obj->remove(val);
51+
* int param_3 = obj->getRandom();
52+
*/

0 commit comments

Comments
 (0)