剑指 Offer 30. 包含min函数的栈

时间:2020-12-15 00:09:00   收藏:0   阅读:35
class MinStack {
    Stack<Integer> A,B;
    /** initialize your data structure here. */
    public MinStack() {
             A = new Stack<>();
             B = new Stack<>();
    }
    
    public void push(int x) {
            A.add(x);
            if(B.empty() || B.peek()>=x)
            B.add(x);
    }
    
    public void pop() {
            if(A.pop().equals(B.peek()))
            B.pop();
    }
    
    public int top() {
        return A.peek();
    }
    
    public int min() {
            return B.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.min();
 */

 

原文:https://www.cnblogs.com/peanut-zh/p/14136396.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!