-
Notifications
You must be signed in to change notification settings - Fork 0
/
design_hashset.cpp
114 lines (99 loc) · 2.16 KB
/
design_hashset.cpp
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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
/*
* =====================================================================================
*
* Filename: design_hashset.cpp
*
* Description: Design HashSet.
* Design a HashSet without using any built-in hash table libraries.
*
* Version: 1.0
* Created: 02/25/19 10:59:29
* Revision: none
* Compiler: gcc
*
* Author: Zhu Xianfeng (), [email protected]
* Organization:
*
* =====================================================================================
*/
#include <stdio.h>
#include <stdlib.h>
#include <list>
#include <vector>
// Bit manipulation
class MyHashSet1 {
public:
MyHashSet1() {
size_ = (1000000 + 1 + 31) / 32;
buf_ = new int[size_]();
}
~MyHashSet1() { delete[] buf_; }
void add(int key) {
int idx = key / 32;
int seq = key % 32;
if (idx < size_) {
buf_[idx] |= (0x1 << seq);
}
}
void remove(int key) {
int idx = key / 32;
int seq = key % 32;
if (idx < size_) {
buf_[idx] &= ~(0x1 << seq);
}
}
bool contains(int key) {
int idx = key / 32;
int seq = key % 32;
if (idx < size_) {
return ((buf_[idx] & (0x1 << seq)) ? true : false);
}
return false;
}
private:
int size_;
int* buf_;
};
// Hash table
class MyHashSet2 {
public:
MyHashSet2() : buckets_(prime) {}
~MyHashSet2() = default;
void add(int key) {
std::list<int>& nums = getBucket(key);
for (const int val : nums) {
if (val == key) {
return;
}
}
nums.push_back(key);
}
void remove(int key) {
std::list<int>& nums = getBucket(key);
nums.remove(key);
}
bool contains(int key) {
std::list<int>& nums = getBucket(key);
for (const int val : nums) {
if (val == key) {
return true;
}
}
return false;
}
private:
std::list<int>& getBucket(int key) {
int hash = key % prime;
return buckets_[hash];
}
private:
const int prime = 997;
std::vector<std::list<int>> buckets_;
};
using MyHashSet = MyHashSet2;
int main(int argc, char* argv[]) {
MyHashSet my_set;
my_set.add(10);
printf("%d\n", my_set.contains(10));
return 0;
}