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.
class MinStack {
private Stack<Integer> stackData = new Stack<Integer>();
private Stack<Integer> stackMin = new Stack<Integer>();
public void push(int x) {
if (stackMin.isEmpty()) {
stackMin.push(x);
} else if (x <= getMin()) {
stackMin.push(x);
}
stackData.push(x);
}
public void pop() {
if (stackData.isEmpty()) {
return;
}
Integer pop = stackData.pop();
if (pop == getMin()) {
stackMin.pop();
}
}
public int top() {
return stackData.peek();
}
public int getMin() {
if (stackMin.isEmpty()) {
return 0;
}
return stackMin.peek();
}
}