155. Min Stack
Last updated
Last updated
time: O(1)
space:O(n)
class MinStack {
// normal stack
// min stack
private Stack<Integer> stack;
private Stack<Integer> min;
/** initialize your data structure here. */
public MinStack() {
stack = new Stack<>();
min = new Stack<>();
}
public void push(int val) {
stack.push(val);
if (min.isEmpty()) {
min.push(val);
} else if (val <= min.peek()) {
min.push(val);
}
}
public void pop() {
int x = stack.pop();
if (x == min.peek()) {
min.pop();
}
}
public int top() {
return stack.peek();
}
public int getMin() {
return min.peek();
}
}
/**
* Your MinStack object will be instantiated and called as such:
* MinStack obj = new MinStack();
* obj.push(val);
* obj.pop();
* int param_3 = obj.top();
* int param_4 = obj.getMin();
*/
in the last step, the stack will be poped into an empty stack!
Integer.MAX_VALUE
class MinStack {
private Stack<Integer> stack;
private int min;
/** initialize your data structure here. */
public MinStack() {
stack = new Stack<>();
min = Integer.MAX_VALUE;
}
public void push(int val) {
if (val <= min) {
stack.push(min);
min = val;
}
stack.push(val);
}
public void pop() {
if (stack.pop() == min) {
min = stack.pop();
}
}
public int top() {
return stack.peek();
}
public int getMin() {
return min;
}
}
/**
* Your MinStack object will be instantiated and called as such:
* MinStack obj = new MinStack();
* obj.push(val);
* obj.pop();
* int param_3 = obj.top();
* int param_4 = obj.getMin();
*/