定义栈的数据结构,请在该类型中实现一个能够得到栈的最小元素的 min 函数在该栈中,调用 min、push 及 pop 的时间复杂度都是 O(1)。
示例:
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.min(); --> 返回 -3.
minStack.pop();
minStack.top(); --> 返回 0.
minStack.min(); --> 返回 -2.
提示:
各函数的调用总次数不超过 20000 次。
代码1:
/**
* initialize your data structure here.
*/
var MinStack = function() {
this.stack=[];
};
/**
* @param {number} x
* @return {void}
*/
MinStack.prototype.push = function(x) {
this.stack.push(x);
};
/**
* @return {void}
*/
MinStack.prototype.pop = function() {
this.stack.pop();
};
/**
* @return {number}
*/
MinStack.prototype.top = function() {
return this.stack[this.stack.length-1];
};
/**
* @return {number}
*/
MinStack.prototype.min = function() {
let index=this.stack.length;
let min=this.stack[index-1];
while(index>=0){
if(this.stack[--index]<min){
min=this.stack[index];
}
}
return min;
};
/**
* 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.min()
*/
代码2:(采用双栈)
/**
* initialize your data structure here.
*/
var MinStack = function() {
this.stack=[];
this.minstack=[Infinity];
};
/**
* @param {number} x
* @return {void}
*/
MinStack.prototype.push = function(x) {
this.stack.push(x);
this.minstack.push(Math.min(this.minstack[this.minstack.length-1],x));
};
/**
* @return {void}
*/
MinStack.prototype.pop = function() {
this.stack.pop();
this.minstack.pop();
};
/**
* @return {number}
*/
MinStack.prototype.top = function() {
return this.stack[this.stack.length-1];
};
/**
* @return {number}
*/
MinStack.prototype.min = 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.min()
*/
思路:这道题的关键就是找栈中最小元素。
第一种暴力寻找,遍历栈中的所有元素进行比较找到最小的元素。
第二种采用双栈的思想:图解(来源力扣)