Last active
August 2, 2020 17:31
-
-
Save sedmo/3df472cbdea2778b7a5032b34b727c9d to your computer and use it in GitHub Desktop.
I took the array of list approach. rbt would have been more optimal on worst case
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
// using chaining | |
class MyHashSet { | |
vector<list<int> *> hashSet; | |
const int CAP = 1000; | |
public: | |
/** Initialize your data structure here. */ | |
// initializing with nullptr allows you not to create unnecessary space until needed i.e. on add | |
MyHashSet() { | |
hashSet = vector<list<int> *>(CAP, nullptr); | |
} | |
void add(int key) { | |
int hash = getHash(key); | |
if(hashSet[hash] == nullptr) | |
hashSet[hash] = new list<int>(); | |
if(contains(key)) | |
return; | |
hashSet[hash]->push_back(key); | |
} | |
void remove(int key) { | |
if(!contains(key)) return; | |
int hash = getHash(key); | |
hashSet[hash]->remove(key); | |
} | |
int getHash(int key) | |
{ | |
return key%capacity; | |
} | |
/** Returns true if this set contains the specified element */ | |
// each chain will be max size 10 since there would be max 10k operations | |
bool contains(int key) { | |
int hash = getHash(key); | |
if(hashSet[hash] == nullptr) return false; | |
for(auto &temp : *hashSet[hash]) | |
{ | |
if(temp == key) return true; | |
} | |
return false; | |
} | |
}; | |
/** | |
* Your MyHashSet object will be instantiated and called as such: | |
* MyHashSet* obj = new MyHashSet(); | |
* obj->add(key); | |
* obj->remove(key); | |
* bool param_3 = obj->contains(key); | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment