zoukankan      html  css  js  c++  java
  • 最小栈问题:题目描述:设计一个支持 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 ]

    }

  • 相关阅读:
    3288 积木大赛
    3284 疯狂的黄大神
    1531 山峰
    1018 单词接龙
    1432 总数统计
    1507 酒厂选址
    1063 合并果子
    几个sort不能过的题目
    poj 2245 Lotto
    求两圆相交面积模板
  • 原文地址:https://www.cnblogs.com/qqfontofweb/p/14993529.html
Copyright © 2011-2022 走看看