MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin(); --> Returns -3.
minStack.pop();
minStack.top(); --> Returns 0.
minStack.getMin(); --> Returns -2.
public class MinStack {
Stack<Integer> stk;
int min;
/** initialize your data structure here. */
public MinStack() {
stk = new Stack<Integer>();
min = Integer.MAX_VALUE;
}
public void push(int x) {
if(x <= min){
stk.push(min);
min = x;
}
stk.push(x);
}
public void pop() {
if(stk.peek() == min){
stk.pop();
min = stk.pop();
} else {
stk.pop();
}
}
public int top() {
return stk.peek();
}
public int getMin() {
return min;
}
}
public class MinStack {
ArrayDeque<Integer> stack, min;
public MinStack() {
this.stack = new ArrayDeque<Integer>();
this.min = new ArrayDeque<Integer>();
}
public void push(int x) {
stack.push(x);
if(min.isEmpty() || x <= min.peek()){
min.push(x);
}
}
public void pop() {
if(stack.isEmpty()){
return;
}
if(min.peek().equals(stack.peek())){
min.pop();
}
stack.pop();
}
public int top() {
return stack.peek();
}
public int getMin() {
return min.peek();
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。