【解题思路】
使用两个队列来实现栈的操作:压栈、弹出、求栈中元素的最小值。
新建一个队列:
Deque<Integer> que1;
Deque<Integer> que2;
que1 = new ArrayDeque<>();
que2 = new ArrayDeque<>();
class MinStack {
Deque<Integer> que1;
Deque<Integer> que2;
int min;
/** initialize your data structure here. */
public MinStack() {
que1 = new ArrayDeque<>();
que2 = new ArrayDeque<>();
}
public void push(int x) {
if(que1.size() == 0 || x < min)
{
min = x;
}
que1.offer(x);
}
public void pop() {
while(que1.size()> 1)
{
que2.offer(que1.poll());
}
if(min == que1.peek())
{
min = 2147483647;
Deque<Integer> que3 = new ArrayDeque<>();
while(que2.size() > 0)
{
if(que2.peek() < min)
{
min = que2.peek();
}
que3.offer(que2.poll());
}
que2 = que3;
}
que1.poll();
while(que2.size() > 0)
{
que1.offer(que2.poll());
}
}
public int top() {
return que1.peekLast();
}
public int min() {
return min;
}
}
/**
* Your MinStack object will be instantiated and called as such:
* MinStack obj = new MinStack();
* obj.push(x);
* obj.pop();
* int param_3 = obj.top();
* int param_4 = obj.min();
*/