思路

  • 我们使用两个栈:
  • 一个栈存放全部的元素,push,pop都是正常操作这个正常栈。
  • 另一个存放最小栈。 每次push,如果比最小栈的栈顶还小,我们就push进最小栈,否则不操作
  • 每次pop的时候,我们都判断其是否和最小栈栈顶元素相同,如果相同,那么我们pop掉最小栈的栈顶元素即可

    关键点

  • 往minstack中 push的判断条件。 应该是stack为空或者x小于等于minstack栈顶元素 ``` /**

    • initialize your data structure here. */ var MinStack = function() { this.stack = [] this.minStack = [] };

/**

  • @param {number} x
  • @return {void} */ MinStack.prototype.push = function(x) { this.stack.push(x) const len = this.minStack.length - 1 if(this.minStack.length === 0 || x <= this.minStack[len]) {
    1. this.minStack.push(x)
    } };

/**

  • @return {void} */ MinStack.prototype.pop = function() { const x = this.stack.pop() if (x !== void 0 && x === this.minStack[this.minStack.length - 1]) {
     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() */ ```