zoukankan      html  css  js  c++  java
  • Leetcode Min Stack

    Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.

    • push(x) -- Push element x onto stack.
    • pop() -- Removes the element on top of the stack.
    • top() -- Get the top element.
    • getMin() -- Retrieve the minimum element in the stack.

    解题思路:

    比较直观。用一个min stack专门存放最小值,如果有比它小或是相等的(有多个平行的最小值都要单独存放,否则pop后会出问题),

    则存放其到minstack.


    Java code:

    class MinStack {
        Stack<Integer> elements = new Stack<Integer>();  
        Stack<Integer> minStack = new Stack<Integer>();  
          
        public void push(int x) {
           elements.push(x);
           if(minStack.isEmpty() || x <= minStack.peek()){
               minStack.push(x);
           }
        }
    
        public void pop() {
           if(elements.isEmpty()){
               return;
           }
           if((int)elements.peek() == (int)(minStack.peek())){
               minStack.pop();
           }
           elements.pop();
        }
    
        public int top() {
            return elements.peek();
        }
    
        public int getMin() {
            return minStack.peek();
        }
    }

    Reference:

    1. http://www.cnblogs.com/yuzhangcmu/p/4106783.html

  • 相关阅读:
    事物的五种传播机制与七种传播行为
    Spring jdbcTemplate
    SpriingMVC执行流程结构
    SpringMVC视图解析器
    promise的基本使用和理解
    集合set的类型转换
    数据结构小结一
    Dotween的一些常用方法记录
    线程与进程的解释
    反射和特性
  • 原文地址:https://www.cnblogs.com/anne-vista/p/4865637.html
Copyright © 2011-2022 走看看