Last active
August 2, 2020 07:14
-
-
Save RP-3/749e85ac5fc69ea6d5a74e2b8ddbc946 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| /** | |
| * 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