-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathLC0705.cpp
More file actions
executable file
·50 lines (42 loc) · 1.09 KB
/
LC0705.cpp
File metadata and controls
executable file
·50 lines (42 loc) · 1.09 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
/*
Problem Statement: https://leetcode.com/problems/design-hashset/
Space: O(n)
Author: Mohammed Shoaib, github.com/Mohammed-Shoaib
|---------------|--------------------|-------|
| Operations | Time | Space |
|---------------|--------------------|-------|
| MyHashSet() | O(1) | O(1) |
| add(key) | O(n), average O(1) | O(1) |
| remove(key) | O(n), average O(1) | O(1) |
| contains(key) | O(n), average O(1) | O(1) |
|---------------|--------------------|-------|
*/
class MyHashSet {
private:
int prime;
vector<list<int>> table;
int hash(int key) {
return key % prime;
}
list<int>::iterator search(int key) {
int h = hash(key);
return find(table[h].begin(), table[h].end(), key);
}
public:
MyHashSet() : prime(10007), table(prime) {}
void add(int key) {
int h = hash(key);
if (!contains(key))
table[h].push_back(key);
}
void remove(int key) {
int h = hash(key);
auto it = search(key);
if (it != table[h].end())
table[h].erase(it);
}
bool contains(int key) {
int h = hash(key);
return search(key) != table[h].end();
}
};