Leetcode155实现最小堆

描述:

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

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

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. */
    Stack stack1 =null;
    Stack stack2 = null;
    public MinStack() {
        stack1 =  new Stack<>();
        stack2 =  new Stack<>();
    }
    
    public void push(int x) {
        stack1.push(x);
        if(stack2.isEmpty() || x <= stack2.peek()){
            stack2.push(x);
        }
    }
    
    public void pop() {
        int x  = stack1.pop();
        //如果右边是当前所弹出的数,就将右边的数也弹出来
            if (x == stack2.peek()) {
                stack2.pop();
            }
    }
    
    public int top() {
            return stack1.peek();
    }
    
    public int getMin() {
            return stack2.peek();
    }
}

你可能感兴趣的:(LeetCode)