leetcode155

    注意:需保证 getMin 的时间复杂度为 O(1)。

    搞一个从栈底到栈顶递减的栈(递减栈),

    • 当有新元素入栈时,如果该元素小于或者等于递减栈的栈顶元素,则将该元素放入递减栈。
    • 当有元素出栈时,如果出栈的元素等于递减栈的栈顶元素,则该元素也要从递减栈里出栈。
    • 递减栈的栈顶元素即是最小栈的最小值。 ```javascript /**
      • initialize your data structure here. */ var MinStack = function() { this.items = []; this.stack = []; };

    /**

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

    /**

    • @return {void} */ MinStack.prototype.pop = function() { const num = this.items.pop(); if(num === this.stack[this.stack.length-1]){
      1. this.stack.pop();
      } };

    /**

    • @return {number} */ MinStack.prototype.top = function() { return this.items[this.items.length - 1]; };

    /**

    • @return {number} */ MinStack.prototype.getMin = function() { return this.stack[this.stack.length - 1] };

    ```