zoukankan      html  css  js  c++  java
  • 155. 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.

    Example:

    MinStack minStack = new MinStack();
    minStack.push(-2);
    minStack.push(0);
    minStack.push(-3);
    minStack.getMin();   --> Returns -3.
    minStack.pop();
    minStack.top();      --> Returns 0.
    minStack.getMin();   --> Returns -2.
    
    //Approach 1: using two stack, Time: O(n), Space: O(n)
    class MinStack {
        Stack<Integer> s;
        Stack<Integer> m;
        /** initialize your data structure here. */
        public MinStack() {
            s = new Stack<Integer>();
            m = new Stack<Integer>();
        }
        
        public void push(int x) {
            s.push(x);
            
            if (m.isEmpty() || x <= m.peek()) {//不要忘记判断m是否为空
                m.push(x);
            }
        }
        
        public void pop() {
            int p = s.pop();
            
            if (!m.isEmpty() && p == m.peek()) {
                m.pop();
            }
        }
        
        public int top() {
            return s.peek();
        }
        
        public int getMin() {
            return m.peek();
        }
    }
    
    //Approach 2: using one stack, Time: O(n), Space: O(n)
    //思路就是记录一个global的min,每次当x小于min时,先把min入栈然后x入栈,这样当出栈的是min时,在pop一次就相当于找到之前的min
    class MinStack {
        Stack<Integer> s;
        int min = Integer.MAX_VALUE;
        /** initialize your data structure here. */
        public MinStack() {
            s = new Stack<Integer>();
        }
        
        public void push(int x) {
            if (x <= min) {
                s.push(min);
                min = x;
            }
            s.push(x);
        }
        
        public void pop() {
            if (s.pop() == min) {
               min = s.pop();
            }
        }
        
        public int top() {
            return s.peek();
        }
        
        public int getMin() {
            return min;
        }
    }
  • 相关阅读:
    LINUX下使用crontab进行RMAN备份实验
    cocos2d-x 通过JNI实现c/c++和Android的java层函数互调
    整型与字符型之间转化
    MFC的最大化,最小化,关闭
    [置顶] IT屌丝的离职申请
    The Priest Mathematician
    jQuery入门学习贴
    poj3308Paratroopers(最小割)
    Nginx 开启 debug 日志的办法
    关于产品的一些思考——(四十二)网易之有道云笔记协同版
  • 原文地址:https://www.cnblogs.com/jessie2009/p/9815787.html
Copyright © 2011-2022 走看看