O(nlogN) PriorityQueue.
public class MinStack {
PriorityQueue<Integer> minHeap;
Stack<Integer> stack;
/** initialize your data structure here. */
public MinStack() {
minHeap = new PriorityQueue<Integer>();
stack = new Stack<Integer>();
}
public void push(int x) {
stack.push(x);
minHeap.offer(x);
}
public void pop() {
minHeap.remove(stack.peek()); // o(logN)
stack.pop();
}
public int top() {
return stack.peek();
}
public int getMin() {
return minHeap.peek();
}
}
O(n)
public class MinStack {
private int min;
private Stack<Integer> stack;
/** initialize your data structure here. */
public MinStack() {
min = Integer.MAX_VALUE;
stack = new Stack<Integer>();
}
// Push old minimum first, then push the new minimum on the top
public void push(int x) {
if (x <= min) {
stack.push(min);
min = x;
}
stack.push(x);
}
// If top of the stack equals to min, then the next element is the second minimum, pop it too and update the min value
public void pop() {
if (stack.pop() == min) {
min = stack.pop();
}
}
public int top() {
return stack.peek();
}
public int getMin() {
return min;
}
}