Skip to content

Instantly share code, notes, and snippets.

@RP-3
Last active August 2, 2020 07:14
Show Gist options
  • Select an option

  • Save RP-3/749e85ac5fc69ea6d5a74e2b8ddbc946 to your computer and use it in GitHub Desktop.

Select an option

Save RP-3/749e85ac5fc69ea6d5a74e2b8ddbc946 to your computer and use it in GitHub Desktop.
/**
* Initialize your data structure here.
*/
var MyHashSet = function(size=10_000) {
this.size = size;
this.storage = new Array(size).fill(0).map(() => []);
};
/**
* @param {number} key
* @return {void}
*/
MyHashSet.prototype.add = function(key) {
const index = key % this.size;
for(let i=0; i<this.storage[index].length; i++){
if(this.storage[index][i] === key) return;
}
this.storage[index].push(key);
};
/**
* @param {number} key
* @return {void}
*/
MyHashSet.prototype.remove = function(key) {
const index = key % this.size;
const sublist = this.storage[index];
const len = sublist.length;
for(let i=0; i<len; i++){
if(sublist[i] === key){
if(i !== len-1){
[sublist[i], sublist[len-1]] = [sublist[len-1], sublist[i]];
}
return sublist.pop();
}
}
};
/**
* Returns true if this set contains the specified element
* @param {number} key
* @return {boolean}
*/
MyHashSet.prototype.contains = function(key) {
const index = key % this.size;
for(let i=0; i<this.storage[index].length; i++){
if(this.storage[index][i] === key) return true;
}
return false;
};
/**
* Your MyHashSet object will be instantiated and called as such:
* var obj = new MyHashSet()
* obj.add(key)
* obj.remove(key)
* var param_3 = obj.contains(key)
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment