diff --git a/155MinStack.js b/155MinStack.js new file mode 100644 index 00000000..1b30801a --- /dev/null +++ b/155MinStack.js @@ -0,0 +1,53 @@ +// Time Complexity : O(1) +// Space Complexity : O(n) +// Did this code successfully run on Leetcode : Yes +// Any problem you faced while coding this : No + +var MinStack = function () { + this.mainStack = []; + this.minStack = []; +}; + +/** + * @param {number} val + * @return {void} + */ +MinStack.prototype.push = function (val) { + this.mainStack.push(val); + const minVal = + this.minStack.length === 0 + ? val + : Math.min(val, this.minStack[this.minStack.length - 1]); + this.minStack.push(minVal); +}; + +/** + * @return {void} + */ +MinStack.prototype.pop = function () { + this.mainStack.pop(); + this.minStack.pop(); +}; + +/** + * @return {number} + */ +MinStack.prototype.top = function () { + return this.mainStack[this.mainStack.length - 1]; +}; + +/** + * @return {number} + */ +MinStack.prototype.getMin = function () { + return this.minStack[this.minStack.length - 1]; +}; + +/** + * Your MinStack object will be instantiated and called as such: + * var obj = new MinStack() + * obj.push(val) + * obj.pop() + * var param_3 = obj.top() + * var param_4 = obj.getMin() + */ diff --git a/705DesignHashSet.js b/705DesignHashSet.js new file mode 100644 index 00000000..f4124c19 --- /dev/null +++ b/705DesignHashSet.js @@ -0,0 +1,62 @@ +// Time Complexity : O(1) +// Space Complexity : O(n) +// Did this code successfully run on Leetcode : Yes +// Any problem you faced while coding this : No + +var MyHashSet = function () { + this.size = 1009; + this.buckets = new Array(this.size); + for (let i = 0; i < this.size; i++) { + this.buckets[i] = []; + } +}; + +/** + * @param {number} key + * @return {void} + */ + +MyHashSet.prototype.hash1 = function (key) { + return key % this.size; +}; +MyHashSet.prototype.hash2 = function (key) { + return Math.floor(key / this.size); +}; +MyHashSet.prototype.add = function (key) { + const h1 = this.hash1(key); + const h2 = this.hash2(key); + // if(!this.buckets[h1]) + //this.buckets[h1] = new Array(993).fill(false) + this.buckets[h1][h2] = true; +}; + +/** + * @param {number} key + * @return {void} + */ +MyHashSet.prototype.remove = function (key) { + const h1 = this.hash1(key); + const h2 = this.hash2(key); + if (this.buckets[h1]) this.buckets[h1][h2] = false; +}; + +/** + * @param {number} key + * @return {boolean} + */ +MyHashSet.prototype.contains = function (key) { + const h1 = this.hash1(key); + const h2 = this.hash2(key); + if (this.buckets[h1]) + if (this.buckets[h1][h2]) return true; + else return false; + else 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) + */