美文网首页
剑指 Offer 第30题:包含min函数的栈

剑指 Offer 第30题:包含min函数的栈

作者: 放开那个BUG | 来源:发表于2022-07-20 16:49 被阅读0次

    1、前言

    题目描述

    2、思路

    3、代码

    class MinStack {
    
        private Stack<Integer> stack1 = new Stack<Integer>();
        private Stack<Integer> stack2 = new Stack<Integer>();
    
        /** initialize your data structure here. */
        public MinStack() {
    
        }
        
        public void push(int x) {
            stack1.push(x);
            if(!stack2.isEmpty() && stack2.peek() < x){
                return;
            }
            stack2.push(x);
        }
        
        public void pop() {
            if(stack1.pop().equals(stack2.peek())){
                stack2.pop();
            }
        }
        
        public int top() {
            return stack1.peek();
        }
        
        public int min() {
            return stack2.peek();
        }
    }
    

    相关文章

      网友评论

          本文标题:剑指 Offer 第30题:包含min函数的栈

          本文链接:https://www.haomeiwen.com/subject/lznbbrtx.html