力扣【155】最小栈

题目:

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

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

题解:采用辅助栈,用来存放最小值。(剑指offer第二十题)

class MinStack {

    Stack<Integer> datastack = new Stack<>();
    Stack<Integer> minstack = new Stack<>();

    public MinStack() {
        minstack.push(Integer.MAX_VALUE);
    }

    public void push(int x) {
        datastack.push(x);
        minstack.push(Math.min(minstack.peek(), x));
    }
    
    public void pop() {
        datastack.pop();
        minstack.pop();
    }

    public int top() {
        return datastack.peek();
    }

    public int getMin() {
        return minstack.peek();
    }
}

猜你喜欢

转载自blog.csdn.net/qq1922631820/article/details/111056845