Skip to content

Instantly share code, notes, and snippets.

@dimitriye98
Created August 3, 2020 03:18
Show Gist options
  • Save dimitriye98/3bf38b32a83d319959f73a4e4927364a to your computer and use it in GitHub Desktop.
Save dimitriye98/3bf38b32a83d319959f73a4e4927364a to your computer and use it in GitHub Desktop.
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