设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。
push(x) – 将元素 x 推入栈中。
pop() – 删除栈顶的元素。
top() – 获取栈顶元素。
getMin() – 检索栈中的最小元素。
用两个stack实现,一个存数,一个存最小值
class MinStack {
Deque<Integer> stack1;
Deque<Integer> stack2;
/** initialize your data structure here. */
public MinStack() {
stack1=new ArrayDeque<>();
stack2=new ArrayDeque<>();
}
public void push(int x) {
stack1.push(x);
if(stack2.isEmpty()){
stack2.push(x);
}
else{
stack2.push(Math.min(x,stack2.peek()));
}
}
public void pop() {
stack1.pop();
stack2.pop();
}
public int top() {
return stack1.peek();
}
public int getMin() {
return stack2.peek();
}
}