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 ]

    }

  • 相关阅读:
    利用scanf函数修改内存中任意位置内容
    TSql
    完整性约束及其违约处理
    实现关机、重启、注销
    建立索引的原则
    我只想安静的大便
    格式化GridView特定的值
    SELECT语句执行顺序解析
    CPU对存储器的读写
    Linux常用97条命令
  • 原文地址:https://www.cnblogs.com/qqfontofweb/p/14993529.html
Copyright © 2011-2022 走看看