Thinking process
Get the min?
- using heap, but the pop() is gonna be O(log n)
Using two stacks
- one is regular stack, another only saves current minimum
Mistakes
before using peek(), check whether the stack is empty!!!
public class MinStack {
private Stack<Integer> stack;
private Stack<Integer> minStack;
public MinStack() {
stack = new Stack<Integer>();
minStack = new Stack<Integer>();
}
public void push(int number) {
stack.push(number);
if (minStack.isEmpty()) {
minStack.push(number);
} else {
minStack.push(Math.min(number, minStack.peek()));
}
}
public int pop() {
minStack.pop();
return stack.pop();
}
public int min() {
return minStack.peek();
}
}
To improve the code above, save extra space, but space complexity remains the same
public class MinStack {
private Stack<Integer> stack;
private Stack<Integer> minStack;
public MinStack() {
stack = new Stack<Integer>();
minStack = new Stack<Integer>();
}
public void push(int number) {
stack.push(number);
if (minStack.empty() == true)
minStack.push(number);
else
if (minStack.peek() >= number)
minStack.push(number);
}
public int pop() {
if (stack.peek().equals(minStack.peek()) )
minStack.pop();
return stack.pop();
}
public int min() {
return minStack.peek();
}
}