[LeetCode] Design HashSet

705. Design HashSet

Design a HashSet without using any built-in hash table libraries.

Implement MyHashSet class:

  • void add(key) Inserts the value key into the HashSet.
  • bool contains(key) Returns whether the value key exists in the HashSet or not.
  • void remove(key) Removes the value key in the HashSet. If key does not exist in the HashSet, do nothing.
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
#define BUCKET 31
class MyHashSet {
set<int> s[BUCKET];
public:
MyHashSet() {

}

void add(int key) {
s[key % BUCKET].insert(key);
}

void remove(int key) {
s[key % BUCKET].erase(key);
}

bool contains(int key) {
return s[key % BUCKET].count(key);
}
};

/**
* Your MyHashSet object will be instantiated and called as such:
* MyHashSet* obj = new MyHashSet();
* obj->add(key);
* obj->remove(key);
* bool param_3 = obj->contains(key);
*/
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/04/21/PS/LeetCode/design-hashset/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.