Leetcode 155. 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.

思路:实现一个能随时返回当前栈中最小值的栈,借助一个辅助栈,这个栈负责存储最小值,当有新元素入栈时,判断新元素和辅助栈顶的大小关系,确定辅助栈入栈元素。

private Stack<Integer> stack;
private Stack<Integer> minStack;

public MinStack() {
    this.stack = new Stack<>();
    this.minStack = new Stack<>();
}

public void push(int x) {
    //stack.push(x);//bug 当push第一个元素的时候,如果stackpush在前,第20行,minStack还是empty,peek()会报错
    if (stack.empty()) {
        minStack.push(x);
    } else {
        minStack.push(Math.min(x, minStack.peek()));
    }
    stack.push(x);
}

public void pop() {
    stack.pop();
    minStack.pop();
}

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

public int getMin() {
    return minStack.peek();
}
    原文作者:ShutLove
    原文地址: https://www.jianshu.com/p/84eac45ee29a
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞