程序员面试金典-面试题 03.02. 栈的最小值

题目:

请设计一个栈,除了常规栈支持的pop与push函数以外,还支持min函数,该函数返回栈元素中的最小值。执行push、pop和min操作的时间复杂度必须为O(1)。


示例:

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 {

    /** initialize your data structure here. */
    public MinStack() {
        stack = new Stack<>();
        min_stack = new Stack();
    }
    
    public void push(int x) {
        if(stack.isEmpty()){
            stack.push(x);
            min_stack.push(x);
        }else{
            stack.push(x);
            if(x < min_stack.peek()){
                min_stack.push(x);
            }else{
                min_stack.push(min_stack.peek());
            }
        }
    }
    
    public void pop() {
        stack.pop();
        min_stack.pop();
    }
    
    public int top() {
        return stack.peek();
    }
    
    public int getMin() {
        return min_stack.peek();
    }

    private Stack<Integer> stack;
    private Stack<Integer> min_stack;
}

/**
 * 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();
 */
原文地址:https://www.cnblogs.com/silentteller/p/12420402.html