zoukankan      html  css  js  c++  java
  • 栈的最小值

    2020-03-23
    栈的最小值

    请设计一个栈,除了常规栈支持的pop与push函数以外,还支持min函数,该函数返回栈元素中的最小值。执行push、pop和min操作的时间复杂度必须为O(1)

    示例:

    MinStack minStack = new MinStack();

    minStack.push(-2);

    minStack.push(0);

    minStack.push(-3);

    minStack.getMin(); --> 返回 -3.

    minStack.pop();

    minStack.top(); --> 返回 0.

    题解:
    思路1: 栈基础
    栈数据格式的基本操作
    /**
     * initialize your data structure here.
     */
    var MinStack = function () {
      this.stack = [];
      this.index = 0;
    };
    
    /** 
     * @param {number} x
     * @return {void}
     */
    MinStack.prototype.push = function (x) {
      this.stack[this.index++] = x; // 最后一项插入
    };
    
    /**
     * @return {void}
     */
    MinStack.prototype.pop = function () {
      this.stack.length = this.index - 1; // 通过length减小删除最后一项
      this.index--;
    };
    
    /**
     * @return {number}
     */
    MinStack.prototype.top = function () { // 返回最后一项
      return this.stack[this.index - 1];
    };
    
    /**
     * @return {number}
     */
    MinStack.prototype.getMin = function () { // 获取最小值
      return Math.min(...this.stack);
    };
    
    /**
     * 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()
     */
  • 相关阅读:
    团队冲刺第二阶段-7
    用户体验评价
    团队冲刺第二阶段-6
    第十四周学习进度报告
    团队冲刺第二阶段-5
    团队冲刺第二阶段-4
    14周课堂测试---找水王
    进度日报14
    进度日报13
    进度日报12
  • 原文地址:https://www.cnblogs.com/lanpang9661/p/12550169.html
Copyright © 2011-2022 走看看