-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathHashSet.cpp
79 lines (77 loc) · 2.51 KB
/
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
#include <iostream>
#include <algorithm>
#include <list>
#include <string>
using namespace std;
template <typename K> class HashSet{
list<K> *bucketArray;
int numBuckets;
int size;
int initialCapacity;
float loadRatio;
public:
HashSet(int initialCapacity=16, float loadFactor = 0.75f){
numBuckets =initialCapacity ;
size = 0;
loadRatio = loadFactor;
bucketArray = new list<K>[numBuckets]();
}
//Function name and variable name cant be same;
int Size() { return size;}
bool isEmpty() { return size == 0;}
int getBucketIndex( K key){
unsigned long long hashCode = std::hash<K>{}(key);
int index = hashCode % numBuckets;
return index;
}
void remove(K key){
int bucketIndex = getBucketIndex(key);
typename list<K> :: iterator removeKey = find (bucketArray[bucketIndex].begin(), bucketArray[bucketIndex].end(), key);
if (removeKey != bucketArray[bucketIndex].end())
{
bucketArray[bucketIndex].erase(removeKey);
size--;
}
}
void add(K key){
int bucketIndex = getBucketIndex(key);
//typename list<K> :: iterator insertKey = find (bucketArray[bucketIndex].begin(), bucketArray[bucketIndex].end(), key);
auto insertKey = find (bucketArray[bucketIndex].begin(), bucketArray[bucketIndex].end(), key);
if (insertKey != bucketArray[bucketIndex].end())
{
return ;
}
bucketArray[bucketIndex].emplace_back(key);
size++;
ensureCapacity();
}
void ensureCapacity(){
if((1.0*size)/numBuckets >= loadRatio){
list<K> *temp = bucketArray;
int oldBuckets = numBuckets;
numBuckets = 2 * numBuckets;
bucketArray = new list<K>[numBuckets]();
size = 0;
for(int id = 0;id <oldBuckets; id++){
for ( auto listKey: temp[id])
add(listKey);
temp[id].clear();
}
}
}
};
int main(){
HashSet<string> map;
map.add(string("this"));
cout << map.Size() <<endl;
map.add(string("coder"));
cout << map.Size() <<endl;
map.add(string("this"));
cout << map.Size() <<endl;
map.add(string("hi"));
cout <<"Size:"<< map.Size() <<endl;
map.remove("this");
cout <<"Size:" << map.Size() <<endl;
cout <<"Empty :" << map.isEmpty() <<endl;
return 0;
}