File tree 1 file changed +52
-0
lines changed
10 October LeetCode Challenge 2021
1 file changed +52
-0
lines changed Original file line number Diff line number Diff line change
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
+ */
You can’t perform that action at this time.
0 commit comments