Thursday, April 20, 2017
Min Stack
Version #1 Always push to the minStack
public class MinStack {
private Stack<Integer> minStack;
private Stack<Integer> stack;
public MinStack() {
// do initialize if necessary
minStack = new Stack<>();
stack = new Stack<>();
}
public void push(int number) {
// write your code here
if (minStack.isEmpty()) {
minStack.push(number);
} else {
minStack.push(Math.min(number, minStack.peek()));
}
stack.push(number);
}
public int pop() {
// write your code here
minStack.pop();
return stack.pop();
}
public int min() {
// write your code here
return minStack.peek();
}
}
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment