04-01.最小栈

题目

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

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

代码

class MinStack {

    private Stack<Integer> dataStack = new Stack<Integer>();
    private Stack<Integer> minStack = new Stack<Integer>();

    /** initialize your data structure here. */
    public MinStack() {

    }
    
    public void push(int x) {
        dataStack.push(x);
        if(!minStack.isEmpty()){
            if(getMin() <= x){
                minStack.push(getMin());
            }else{
                minStack.push(x);
            }
        }else{
            minStack.push(x);
        }
    }
    
    public void pop() {
        dataStack.pop();
        minStack.pop();
    }
    
    public int top() {
        return dataStack.peek();
    }
    
    public int getMin() {
        return minStack.peek();
    }
}
发布了99 篇原创文章 · 获赞 72 · 访问量 54万+

猜你喜欢

转载自blog.csdn.net/wj123446/article/details/105040164