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.
Use two stacks, one serves as a regular stack, and the other one only store the current minimum value. When pop, pop both of them. And getMin() return the top value of the minimum stack.
class MinStack {
public Stack<Integer> minStack = new Stack<Integer>();
private Stack<Integer> myStack = new Stack<Integer>();
public void push(int x) {
minStack.push(x);
if (myStack.isEmpty() || x < myStack.peek()) {
myStack.push(x);
} else {
myStack.push(myStack.peek());
}
}
public void pop() {
if (!minStack.isEmpty()) {
minStack.pop();
}
if (!myStack.isEmpty()) {
myStack.pop();
}
}
public int top() {
if (minStack.isEmpty()) {
return Integer.MAX_VALUE;
} else {
return minStack.peek();
}
}
public int getMin() {
return myStack.peek();
}
}