设计一个支持 push ,pop ,top 操作,并能在常数时间**内检索到最小元素的栈**

push(x) —— 将元素 x 推入栈中 pop() —— 删除栈顶的元素 top() —— 获取栈顶元素 getMin() —— 检索栈中的最小元素

思路

  1. 额外的栈空间来做
  2. 每次push的时候判断是否比最小栈的栈顶更小
  3. 更小就push
  4. 其他就是正常栈操作 ```javascript /**
    • initialize your data structure here. */ var MinStack = function () { this.stack = []; // 维护额外的最小栈 this.min_stack = []; };

MinStack.prototype.push = function (x) { this.stack.push(x); // push的时候顺带照顾最小栈就行了 if (x <= this.getMin() || this.min_stack.length == 0) { this.min_stack.push(x); } };

MinStack.prototype.pop = function () { let out = this.stack.pop(); if (this.getMin() == out) { this.min_stack.pop(); } };

MinStack.prototype.top = function () { return this.stack[this.stack.length - 1] };

MinStack.prototype.getMin = function () { return this.min_stack[this.min_stack.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() */ ```