Created
August 3, 2020 03:18
-
-
Save dimitriye98/3bf38b32a83d319959f73a4e4927364a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class MyHashSet { | |
struct Entry { | |
int value; | |
Entry* next; | |
}; | |
Entry** buckets; | |
int capacity; | |
std::hash<int> hasher; | |
void removeNode(Entry** node) { | |
Entry* next = (*node)->next; | |
Entry* danglingNode = *node; | |
*node = next; | |
delete danglingNode; | |
} | |
public: | |
/** Initialize your data structure here. */ | |
MyHashSet() { | |
buckets = new Entry*[64] {nullptr}; | |
capacity = 64; | |
} | |
void add(int key) { | |
Entry** bucket = &buckets[hasher(key) % capacity]; | |
while (*bucket != nullptr) { | |
if ((*bucket)->value == key) { return; } | |
bucket = & (*bucket)->next; | |
} | |
*bucket = new Entry{key, nullptr}; | |
} | |
void remove(int key) { | |
Entry** bucket = &buckets[hasher(key) % capacity]; | |
while (*bucket != nullptr) { | |
if ((*bucket)->value == key) { | |
return removeNode(bucket); | |
} | |
bucket = & (*bucket)->next; | |
} | |
} | |
/** Returns true if this set contains the specified element */ | |
bool contains(int key) { | |
Entry** bucket = &buckets[hasher(key) % capacity]; | |
while (*bucket != nullptr) { | |
if ((*bucket)->value == key) { return true; } | |
bucket = & (*bucket)->next; | |
} | |
return false; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment