zoukankan      html  css  js  c++  java
  • 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();
        }
    }
  • 相关阅读:
    配置步骤
    swap区
    Oracle的left join中on和where的区别
    drop与truncate
    关于trace
    oracle执行计划连接方式
    oracle系统结构
    查询存档
    oracle统计信息
    分区索引
  • 原文地址:https://www.cnblogs.com/lilyfindjobs/p/4088620.html
Copyright © 2011-2022 走看看