Created
August 3, 2020 07:01
-
-
Save dimitriye98/71477d9b4b225da9294cf2bbd37d3d9b 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
const int EMPTY = -1; | |
const int TOMBSTONE = -2; | |
class MyHashSet { | |
int* buckets; | |
size_t size = 0; | |
size_t capacity; | |
void resize() { | |
int* oldBuckets = buckets; | |
size_t oldCapacity = capacity; | |
capacity *= 2; | |
buckets = new int[capacity]; | |
std::fill_n(buckets, capacity, EMPTY); | |
for (size_t i = 0; i < oldCapacity; ++i) { | |
addImpl(oldBuckets[i]); | |
} | |
} | |
void addImpl(int key) { | |
for (size_t i = key % capacity; i < capacity; ++i) { | |
if (buckets[i] == EMPTY || buckets[i] == TOMBSTONE) { | |
buckets[i] = key; | |
return; | |
} | |
} | |
for (size_t i = 0; i < key % capacity; ++i) { | |
if (buckets[i] == EMPTY || buckets[i] == TOMBSTONE) { | |
buckets[i] = key; | |
return; | |
} | |
} | |
} | |
public: | |
/** Initialize your data structure here. */ | |
MyHashSet() { | |
capacity = 64; | |
buckets = new int[capacity]; | |
std::fill_n(buckets, capacity, EMPTY); | |
} | |
void add(int key) { | |
// cout << "add: " << key << endl; | |
if (size > capacity * 0.9) { | |
resize(); | |
} | |
addImpl(key); | |
++size; | |
} | |
void remove(int key) { | |
// cout << "del: " << key << endl; | |
for (size_t i = key % capacity; i < capacity; ++i) { | |
if (buckets[i] == key) { | |
buckets[i] = TOMBSTONE; | |
} else if (buckets[i] == EMPTY) { | |
return; | |
} | |
} | |
for (size_t i = 0; i < key % capacity; ++i) { | |
if (buckets[i] == key) { | |
buckets[i] = TOMBSTONE; | |
} else if (buckets[i] == EMPTY) { | |
return; | |
} | |
} | |
} | |
/** Returns true if this set contains the specified element */ | |
bool contains(int key) { | |
// cout << "chk: " << key << endl; | |
for (size_t i = key % capacity; i < capacity; ++i) { | |
if (buckets[i] == key) { | |
return true; | |
} else if (buckets[i] == EMPTY) { | |
return false; | |
} | |
} | |
for (size_t i = 0; i < key % capacity; ++i) { | |
if (buckets[i] == key) { | |
return true; | |
} else if (buckets[i] == EMPTY) { | |
return false; | |
} | |
} | |
return false; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment