问题描述
定义栈的数据结构,请在该类型中实现一个能够得到栈的最小元素的 min 函数在该栈中,调用 min、push 及 pop 的时间复杂度都是 O(1)。
思路
使用两个栈,栈a存放每次push的元素,栈B存放push序列的非递增序列,查找最小值是,每次直接从栈Bpeek元素即可。需要注意的地方是栈存储Integer元素,比较大小时使用equals。
代码
class MinStack {
Stack<Integer> a = new Stack<>();
Stack<Integer> b = new Stack<>();
/** initialize your data structure here. */
public MinStack() {
}
public void push(int x) {
a.push(x);
if(b.isEmpty() || x <= b.peek()) b.push(x);
}
public void pop() {
if(a.pop().equals(b.peek())) {
b.pop();
}
}
public int top() {
return a.peek();
}
public int min() {
return b.peek();
}
}