zoukankan      html  css  js  c++  java
  • LeetCode155.最小栈

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

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

    示例:

    MinStack minStack = new MinStack();
    minStack.push(-2);
    minStack.push(0);
    minStack.push(-3);
    minStack.getMin();   --> 返回 -3.
    minStack.pop();
    minStack.top();      --> 返回 0.
    minStack.getMin();   --> 返回 -2.
    class MinStack {
    
        private Stack<Integer> stack;
        private Stack<Integer> stackMin;
        /** initialize your data structure here. */
        public MinStack() {
            this.stack = new Stack<Integer>();
            this.stackMin = new Stack<Integer>();
        }
        
        public void push(int x) {
            stack.push(x);
            if (!stackMin.isEmpty()) {
                int min = stackMin.peek();
                if (x<=min) {
                    stackMin.push(x);
                }
            } else {
                this.stackMin.push(x);
            }
        }
        
        public void pop() {
            int value = this.stack.pop();
            if (!this.stackMin.isEmpty()) {
                if (value == stackMin.peek()) {
                    stackMin.pop();
                }
            }
        }
        
        public int top() {
            int value = this.stack.peek();
            return value;
        }
        
        public int getMin() {
            return this.stackMin.peek();
        }
    }
    
    /**
     * Your MinStack object will be instantiated and called as such:
     * MinStack obj = new MinStack();
     * obj.push(x);
     * obj.pop();
     * int param_3 = obj.top();
     * int param_4 = obj.getMin();
     */
  • 相关阅读:
    [][]
    Spark笔记04
    Spark笔记03
    Spark笔记02
    Spark笔记01
    【熟能生巧】使用Screw快速生成数据库文档
    记一次关于jdbcTemplate.queryForList快速Debug及感悟
    【从零单排】Exception实战总结1
    【从零单排】Java性能排查实战模拟
    【从零单排】关于泛型Generic的一些思考
  • 原文地址:https://www.cnblogs.com/airycode/p/9778420.html
Copyright © 2011-2022 走看看