Skip to content
Open

Design2 #2459

Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 50 additions & 0 deletions 232ImplementQueueusingStacks.js
Original file line number Diff line number Diff line change
@@ -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()
*/
79 changes: 79 additions & 0 deletions 706DesignHashMap.js
Original file line number Diff line number Diff line change
@@ -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)
*/