`

Min Stack

阅读更多
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.

实现一个可以返回最小值的堆栈,因为题目要求我们在O(1)的时间复杂度下返回最小值,我们需要用一个堆栈minStack单独来维护最小值,当进行push操作的时候,我们要检查压栈的元素是否是最小值,如果是最小值还要把这个元素放到minStack中去。pop操作的时候要检查出栈的元素是否为最小值,如果为最小值,在minStack中也要将这个元素弹出,getMin操作的时候只需要返回minStack的顶端的元素就可以了,期间不要忘记检查堆栈是否为空。代码如下:
class MinStack {
    Stack<Integer> stack = new Stack<Integer>();
    Stack<Integer> minStack = new Stack<Integer>();
    public void push(int x) {
        stack.push(x);
        if(!minStack.isEmpty()) {
            if(x <= minStack.peek()) {
                minStack.push(x);
            }
        } else {
            minStack.push(x);
        }
    }

    public void pop() {
        if(stack.isEmpty()) return;
        int num = stack.pop();
        if(num == minStack.peek()) {
            minStack.pop();
        }
    }

    public int top() {
        if(stack.isEmpty()) return Integer.MAX_VALUE;
        return stack.peek();
    }

    public int getMin() {
        if(minStack.isEmpty()) 
            return Integer.MAX_VALUE;
        return minStack.peek();
    }
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics