[原题链接](https://leetcode-cn.com/problems/min-stack/solution/qian-duan-shi-tang-ti-jie-chao-hao-li-ji-am9u/) ## 辅助栈 1. stack 支持常规的 push、pop、top 操作。 2. 定义一个辅助栈 resStack ,将最小值一直保持在栈顶,来支持常数时间复杂度获取。 ```js const MinStack = function() { this.stack = []; this.resStack = [Infinity]; }; MinStack.prototype.push = function(x) { this.stack.push(x); this.resStack.push(Math.min(this.resStack[this.resStack.length - 1], x)); }; MinStack.prototype.pop = function() { this.stack.pop(); this.resStack.pop(); }; MinStack.prototype.top = function() { return this.stack[this.stack.length - 1]; }; MinStack.prototype.getMin = function() { return this.resStack[this.resStack.length - 1]; }; ``` - 时间复杂度: O(1) - 空间复杂度: O(n)
Activity