最小栈问题:题目描述:设计一个支持 push ,pop ,top 操作,并能在常数时间内检索到最小元素的栈。

MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin(); --> 返回 -3.
minStack.pop();
minStack.top(); --> 返回 0.
minStack.getMin(); --> 返回 -2.

const minStack = function(){

   this.stack = []

  // 辅助栈,换更少的时间复杂度

   this.stack2 = []

}

minStack.prototype.push = function(x){

     this.stack.push(x) 

   // 如果入栈比辅助栈的栈顶元素小或者相等,则入辅助栈

     if(this.stack2.length ==0 || this.stack2[this.stack.length-1>=x]){

        this.stack2.push(x)

    }

}

minStack.prototype.pop = function(){

// 如果主栈出栈的值小于等于辅助栈栈顶元素,辅助栈也要出栈,确保getMin一直是栈中的最小值

    if(this.stack.pop() == this.stack2[this.stack2.length - 1]){

       return this.stack2.pop()

   }

}

minStack.prototype.top = function(){

    return this.stack[this.stack.length-1]

}

minstack.prototype.getMin = function(){

  return this.stack2[this.stack2.length -1 ]

}

原文地址:https://www.cnblogs.com/qqfontofweb/p/14993529.html