[LeetCode] Insert Delete GetRandom O(1)

380. Insert Delete GetRandom O(1)

Implement the RandomizedSet class:

  • RandomizedSet() Initializes the RandomizedSet object.
  • bool insert(int val) Inserts an item val into the set if not present. Returns true if the item was not present, false otherwise.
  • bool remove(int val) Removes an item val from the set if present. Returns true if the item was present, false otherwise.
  • int getRandom() Returns a random element from the current set of elements (it’s guaranteed that at least one element exists when this method is called). Each element must have the same probability of being returned.
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
class RandomizedSet {
set<int> s;
public:
/** Initialize your data structure here. */
RandomizedSet() {}

/** Inserts a value to the set. Returns true if the set did not already contain the specified element. */
bool insert(int val) {
bool res = !s.count(val);
s.insert(val);
return res;
}

/** Removes a value from the set. Returns true if the set contained the specified element. */
bool remove(int val) {
bool res = s.count(val);
s.erase(val);
return res;
}

/** Get a random element from the set. */
int getRandom() {
return *next(s.begin(), rand() % s.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();
*/
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/05/01/PS/LeetCode/insert-delete-getrandom-o1/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.