• leetcode MinStack


    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

    1, 记得stack的几个函数,isEmpty(),不能用null, equals,还有读stack最上面的数,但是不取出来的peek()

    2,解法,用另外一个stack来计算最小的,最上面的永远是最小的

    class MinStack {
        Stack<Integer> sta=new Stack<Integer>();
        Stack<Integer> minsta=new Stack<Integer>();
        public void push(int x) {
           sta.push(x);
           if(minsta.isEmpty()||x<=minsta.peek()){
               minsta.push(x);
           }
        }
        public void pop() {       
            if(sta.peek().equals(minsta.peek())){
                minsta.pop();
            }
            sta.pop();
        }
    
        public int top() {
            return sta.peek();
        }
    
        public int getMin() {
            return minsta.peek();
        }
    }
  • 相关阅读:
    AMQP协议
    设计模式三:行为型模式
    设计模式二:结构型模式
    设计模式一:创建型模式
    算法进阶
    数据结构
    希尔排序、计数排序、桶排序、基数排序
    归并排序
    python Gevent协程
    python——多进程
  • 原文地址:https://www.cnblogs.com/lilyfindjobs/p/4088620.html
Copyright © 2020-2023  润新知