function MinStack() { this.stack = []; this.helperStack = []; this.len = 0; this.helperLen = 0; } MinStack.prototype.push = function(v) { this.stack.push(v); this.len++; if (!this.helperLen || this.helperStack[this.helperLen - 1] >= v) { this.helperStack.push(v); this.helperLen++; } }; MinStack.prototype.pop = function() { if (this.stack.pop() === this.helperStack[this.helperLen - 1]) { this.helperStack.pop(); this.helperLen--; } this.len--; }; MinStack.prototype.peek = function() { return this.stack[this.len - 1]; }; MinStack.prototype.getMin = function() { return this.helperStack[this.helperLen - 1]; };
这种实现方式主要是借助更多的空间来换取时间性能的提升,借助辅助栈单纯保存比辅助栈内已有元素更小的值(元素)。