-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmyHashSet.cpp
More file actions
78 lines (65 loc) · 1.41 KB
/
myHashSet.cpp
File metadata and controls
78 lines (65 loc) · 1.41 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
class MyHashSet {
public:
MyHashSet() {
hash = vector<bool>(1000007, false);
}
void add(int key) {
hash[key] = true;
}
void remove(int key) {
hash[key] = false;
}
bool contains(int key) {
return hash[key];
}
private:
vector<bool> hash;
};
/**
* 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);
*/
// bitmap as bucket
class MyHashSet {
public:
MyHashSet() {
hash = vector<int>(31252, 0);
}
void add(int key) {
hash[key / 32] |= (1 << (key % 32));
}
void remove(int key) {
hash[key / 32] &= (~((1 << (key % 32))));
}
bool contains(int key) {
return hash[key / 32] & ((1 << (key % 32)));
}
private:
vector<int> hash;
};
class MyHashSet {
public:
int hash(int key) {
int i = key % len;
for (; data[i] != -2 && data[i] != key; i = (i == len - 1)? 0: i + 1);
return i;
}
MyHashSet() {
data = vector<int>(len, -2);
}
void add(int key) {
data[hash(key)] = key;
}
void remove(int key) {
data[hash(key)] = -1;
}
bool contains(int key) {
return data[hash(key)] == key;
}
private:
int len = 13333; // 10000 / 0.75
vector<int> data;
};