zoukankan      html  css  js  c++  java
  • leetcode刷题笔记一百五十五题 最小栈

    leetcode刷题笔记一百五十五题 最小栈

    源地址:155. 最小栈

    问题描述:

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

    push(x) —— 将元素 x 推入栈中。
    pop() —— 删除栈顶的元素。
    top() —— 获取栈顶元素。
    getMin() —— 检索栈中的最小元素。

    示例:

    输入:
    ["MinStack","push","push","push","getMin","pop","top","getMin"]
    [[],[-2],[0],[-3],[],[],[],[]]

    输出:
    [null,null,null,null,-3,null,0,-2]

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

    //使用两个栈构建
    import scala.collection.mutable
    
    class MinStack {
    
      /** initialize your data structure here. */
      private val mins = mutable.Stack[Int]()
      private val stack = mutable.Stack[Int]()
    
      def top (): Int = {
        stack.top
      }
    
      def getMin (): Int = {
        mins.top
      }
    
      def push (x: Int) = {
        if (mins.isEmpty || mins.top >= x)
          mins.push(x)
        stack.push(x)
      }
    
      def pop () = {
        if (mins.top == top)
          mins.pop()
        stack.pop()
      }
    }
    
    //使用链表
    class MinStack() {
    
        /** initialize your data structure here. */
        case class Node (value: Int, min: Int, next: Node)
        var head: Node = null
    
        def push(x: Int) {
            if (head == null) head = Node(x, x, null)
            else  head = Node(x, Math.min(x, head.min), head)
        }
    
        def pop() {
            if (head != null) head = head.next 
        }
    
        def top(): Int = {
            head.value
        }
    
        def getMin(): Int = {
            head.min
        }
    
    }
    
    /**
     * 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()
     */
    
  • 相关阅读:
    切片
    docker基础
    第18课 脚本练习二(找出文件下最大文件)
    第17课 脚本练习一(添加新用户)
    第十四课 脚本编程(重定向+变量)
    第十课 新建共享文件夹
    第九课 Linux文本处理
    第八课 正则表达式
    第七课 VI全屏文本编辑器
    第六课 Linux文件系统文本操作命令
  • 原文地址:https://www.cnblogs.com/ganshuoos/p/13595387.html
Copyright © 2011-2022 走看看