剑指 Offer 30. 包含min函数的栈
难度:简单 语言:JavaScript
题目描述:
定义栈的数据结构,请在该类型中实现一个能够得到栈的最小元素的 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 次
结果
解题思路
定义两个栈,数据栈存入数据,辅助栈存入每次的最小值。
操作 | 数据栈 | 辅助栈 | 最小值 |
---|---|---|---|
压入3 | 3 | 3 | 3 |
压入4 | 3 4 | 3 3 | 3 |
压入2 | 3 4 2 | 3 3 2 | 2 |
弹出2 | 3 4 | 3 3 | 3 |
代码实现
/**
* initialize your data structure here.
*/
var MinStack = function() {
this.dataStack = [];
this.minStack = [];
};
/**
* @param {number} x
* @return {void}
*/
MinStack.prototype.push = function(x) {
this.dataStack.push(x);
if( this.minStack.length == 0 || x < this.minStack[this.minStack.length-1] )
{
this.minStack.push(x);
}
else{
this.minStack.push(this.minStack[this.minStack.length-1]);
}
// 如果不想再将栈底元素重新压入栈中,可以尝试一下如下示例:
// ["MinStack","push","push","top","min","pop","min","top"]
// [[],[1],[2],[],[],[],[],[]]
};
/**
* @return {void}
*/
MinStack.prototype.pop = function() {
this.dataStack.pop();
this.minStack.pop();
};
/**
* @return {number}
*/
MinStack.prototype.top = function() {//题目描述不够清晰,要求应该是将栈顶元素输出,而不是将其出栈
return this.dataStack[this.dataStack.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()
*/