Created
April 17, 2022 07:30
-
-
Save esase/bde4a401070327c73d990420b5427364 to your computer and use it in GitHub Desktop.
Min stack [https://leetcode.com/problems/min-stack]
This file contains 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
var MinStack = function() { | |
this.stack = [] | |
this.historyStack = []; | |
}; | |
/** | |
* @param {number} val | |
* @return {void} | |
*/ | |
MinStack.prototype.push = function(val) { | |
this.stack.push(val); | |
const currentLocalMin = this.getMin(); | |
const historyMin = val !== undefined && currentLocalMin > val || currentLocalMin === undefined | |
? val | |
: currentLocalMin; | |
this.historyStack.push(historyMin); | |
}; | |
/** | |
* @return {void} | |
*/ | |
MinStack.prototype.pop = function() { | |
this.stack.pop(); | |
this.historyStack.pop(); | |
}; | |
/** | |
* @return {number} | |
*/ | |
MinStack.prototype.top = function() { | |
return this.stack[this.stack.length - 1]; | |
}; | |
/** | |
* @return {number} | |
*/ | |
MinStack.prototype.getMin = function() { | |
return this.historyStack[this.historyStack.length - 1]; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment