思路:
使用一个辅助栈存储最小值,使得栈顶的数值是最小的
代码:
class MinStack {
Deque<Integer> A;
Deque<Integer> B;
/** initialize your data structure here. */
public MinStack() {
A=new ArrayDeque<>();
B=new ArrayDeque<>();
}
public void push(int val) {
A.addLast(val);
if(B.isEmpty()||B.peekLast()>=val){
B.addLast(val);
}
}
public void pop() {
int x=A.removeLast();
if(x==B.peekLast()){
B.removeLast();
}
}
public int top() {
return A.peekLast();
}
public int getMin() {
return B.peekLast();
}
}
分解:
1)此题与剑指offer的一题一样
复杂度分析:
时间复杂度:O(N)
空间复杂度:O(N)