Implement a stack with min() function, which will return the smallest number in the stack.
It should support push, pop and min operation all in O(1) cost.
Example
push(1)
pop() // return 1
push(2)
push(3)
min() // return 2
push(1)
min() // return 1
public class MinStack {
Stack<Integer> res, min;
public MinStack() {
res = new Stack<Integer>();
min = new Stack<Integer>();
}
public void push(int number) {
res.push(new Integer(number));
int minVal = min.isEmpty() ? number : Math.min(number, min.peek());
min.push(new Integer(minVal));
}
public int pop() {
min.pop();
return res.pop();
}
public int min() {
return min.peek();
}
}