-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0705-Design_HashSet.cpp
More file actions
94 lines (86 loc) · 2.36 KB
/
0705-Design_HashSet.cpp
File metadata and controls
94 lines (86 loc) · 2.36 KB
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
/*******************************************************************************
* 0705-Design_HashSet.cpp
* Billy.Ljm
* 30 May 2023
*
* =======
* Problem
* =======
* https://leetcode.com/problems/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.
*
* ===========
* My Approach
* ===========
* The keys are stated to be 0 <= key <= 10^6, which is a relatively small range.
* Thus, we can just create a bool vector of 10^6 size, which will just be 1Mb.
* And just remember if the key is inserted or not
*
* This has a time complexity of O(1) and space complexity of O(1), where n is
* the number of keys inserted.
******************************************************************************/
#include <iostream>
#include <vector>
/**
* Hash set
*/
class MyHashSet {
private:
std::vector<bool> hashset; // hashset[i] = true if i is in set
public:
/**
* Instantiates an empty hash set
*/
MyHashSet() {
this->hashset = std::vector<bool>(1e6 + 1, false);
}
/**
* Adds a key to the hash set
*
* @param key key to add
*/
void add(int key) {
this->hashset[key] = true;
}
/**
* Removes a key from the hash set
*
* @param key key to remove
*/
void remove(int key) {
this->hashset[key] = false;
}
/**
* Check if hash set contains a specific key
*
* @param key key to check for
*
* @return true if key is in hash set, false otherwise
*/
bool contains(int key) {
return this->hashset[key];
}
};
/**
* Test cases
*/
int main(void) {
MyHashSet myHashSet = MyHashSet();
myHashSet.add(1); // set = [1]
myHashSet.add(2); // set = [1, 2]
std::cout << std::boolalpha << myHashSet.contains(1) << std::endl; // return True
std::cout << std::boolalpha << myHashSet.contains(3) << std::endl; // return False, (not found)
myHashSet.add(2); // set = [1, 2]
std::cout << std::boolalpha << myHashSet.contains(2) << std::endl; // return True
myHashSet.remove(2); // set = [1]
std::cout << std::boolalpha << myHashSet.contains(2) << std::endl; // return False, (already removed)
return 0;
}