diff --git a/232ImplementQueueusingStacks.js b/232ImplementQueueusingStacks.js new file mode 100644 index 00000000..ec285cb7 --- /dev/null +++ b/232ImplementQueueusingStacks.js @@ -0,0 +1,50 @@ +var MyQueue = function () { + this.inStack = []; + this.outStack = []; +}; + +/** + * @param {number} x + * @return {void} + */ +MyQueue.prototype.push = function (x) { + this.inStack.push(x); +}; + +MyQueue.prototype.transfer = function () { + if (this.outStack.length === 0) + while (this.inStack.length != 0) { + this.outStack.push(this.inStack.pop()); + } +}; +/** + * @return {number} + */ +MyQueue.prototype.pop = function () { + this.transfer(); + return this.outStack.pop(); +}; + +/** + * @return {number} + */ +MyQueue.prototype.peek = function () { + this.transfer(); + return this.outStack[this.outStack.length - 1]; +}; + +/** + * @return {boolean} + */ +MyQueue.prototype.empty = function () { + return this.inStack.length === 0 && this.outStack.length === 0; +}; + +/** + * Your MyQueue object will be instantiated and called as such: + * var obj = new MyQueue() + * obj.push(x) + * var param_2 = obj.pop() + * var param_3 = obj.peek() + * var param_4 = obj.empty() + */ diff --git a/706DesignHashMap.js b/706DesignHashMap.js new file mode 100644 index 00000000..7849b5ec --- /dev/null +++ b/706DesignHashMap.js @@ -0,0 +1,79 @@ +function ListNode(key, value, next = null) { + this.key = key; + this.value = value; + this.next = next; +} + +var MyHashMap = function () { + this.SIZE = 10009; + this.buckets = new Array(this.SIZE).fill(null); +}; + +MyHashMap.prototype.hash = function (key, value) { + return key % this.SIZE; +}; +/** + * @param {number} key + * @param {number} value + * @return {void} + */ +MyHashMap.prototype.put = function (key, value) { + const idx = this.hash(key); + if (!this.buckets[idx]) this.buckets[idx] = new ListNode(-1, -1); + let prev = this.buckets[idx]; + let curr = prev.next; + + while (curr) { + if (curr.key == key) { + curr.value = value; + return; + } + prev = curr; + curr = curr.next; + } + prev.next = new ListNode(key, value); +}; + +/** + * @param {number} key + * @return {number} + */ +MyHashMap.prototype.get = function (key) { + const idx = this.hash(key); + if (!this.buckets[idx]) return -1; + let prev = this.buckets[idx]; + let curr = prev.next; + while (curr) { + if (curr.key == key) return curr.value; + curr = curr.next; + } + return -1; +}; + +/** + * @param {number} key + * @return {void} + */ +MyHashMap.prototype.remove = function (key) { + const idx = this.hash(key); + if (!this.buckets[idx]) return; + + let prev = this.buckets[idx]; + let curr = prev.next; + while (curr) { + if (curr.key === key) { + prev.next = curr.next; + return; + } + prev = curr; + curr = curr.next; + } +}; + +/** + * Your MyHashMap object will be instantiated and called as such: + * var obj = new MyHashMap() + * obj.put(key,value) + * var param_2 = obj.get(key) + * obj.remove(key) + */