思路:辅助栈,存取一个当前最小值的栈
- 最小栈
设计一个支持 push ,pop ,top 操作,并能在常数时间内检索到最小元素的栈。
push(x) —— 将元素 x 推入栈中。
pop() —— 删除栈顶的元素。
top() —— 获取栈顶元素。
getMin() —— 检索栈中的最小元素。
示例:
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin(); --> 返回 -3.
minStack.pop();
minStack.top(); --> 返回 0.
minStack.getMin(); --> 返回 -2.
第一种写法
/**
* initialize your data structure here.
*/
var MinStack = function() {
this.stack = new Array();
this.minStack = new Array();
this.minV = Number.MAX_SAFE_INTEGER
};
/**
* @param {number} x
* @return {void}
*/
MinStack.prototype.push = function(x) {
this.minV = Math.min(this.minV, x)
this.stack.push(x)
this.minStack.push(this.minV)
};
/**
* @return {void}
*/
MinStack.prototype.pop = function() {
let num = this.stack.pop(),
minNum = this.minStack.pop();
if(this.stack.length === 0){
this.minV = Number.MAX_SAFE_INTEGER
}else if(minNum === num){
this.minV = this.minStack.length >= 1 ? this.minStack[this.minStack.length - 1] : Number.MAX_SAFE_INTEGER
}
};
/**
* @return {number}
*/
MinStack.prototype.top = function() {
return this.stack[this.stack.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(x)
* obj.pop()
* var param_3 = obj.top()
* var param_4 = obj.getMin()
*/
第二种写法
/**
* initialize your data structure here.
*/
var MinStack = function() {
this.stack = [];
this.min_stack = [];
};
/**
* @param {number} x
* @return {void}
*/
MinStack.prototype.push = function(x) {
this.stack.push(x);
// 初始化 或 当有更小值入栈
if(this.min_stack.length == 0 || this.min_stack[this.min_stack.length-1] >= x){
this.min_stack.push(x);
}
};
/**
* @return {void}
*/
MinStack.prototype.pop = function() {
// 当出栈值 == 当前最小值时,最小栈的该值删掉
if(this.stack.pop() == this.min_stack[this.min_stack.length-1]){
this.min_stack.pop();
}
};
/**
* @return {number}
*/
MinStack.prototype.top = function() {
return this.stack[this.stack.length-1];
};
/**
* @return {number}
*/
MinStack.prototype.getMin = function() {
return this.min_stack[this.min_stack.length-1];
};
/**
* Your MinStack object will be instantiated and called as such:
* var obj = new MinStack()
* obj.push(x)
* obj.pop()
* var param_3 = obj.top()
* var param_4 = obj.getMin()
*/