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 stack;
private Stack 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();
}

你可能感兴趣的:(Leetcode 155. Min Stack)