设计一个支持 push ,pop ,top 操作,并能在常数时间内检索到最小元素的栈。
push(x) —— 将元素 x 推入栈中。
pop() —— 删除栈顶的元素。
top() —— 获取栈顶元素。
getMin() ——检索栈中的最小元素。
提示:pop、top 和 getMin 操作总是在 非空栈 上调用。
思路:
增加一个辅助栈,每次压入数据时,把当前数据栈中最小的值压入辅助栈,这样辅助栈的栈顶元素一直是数据栈中的最小值。每次弹出也要把辅助栈中的栈顶弹出。
/**
* 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.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()
*/
复杂度分析
- 时间复杂度:对于题目中的所有操作,时间复杂度均为 O(1)。因为栈的插入、删除与读取操作都是O(1),我们定义的每个操作最多调用栈操作两次。
- 空间复杂度:O(n),其中 n 为总操作数。最坏情况下,我们会连续插入 n 个元素,此时两个栈占用的空间为 O(n)。