题目描述:
定义栈的数据结构,请在该类型中实现一个能够得到栈的最小元素的 min 函数在该栈中,调用 min、push 及 pop 的时间复杂度都是 O(1)。
例:

分析:
是找出在栈的最小值,本来想用数组来着,但是要求空间复杂度为O(1),就放弃使用了。用两个栈来进行,第二个栈用来储存最小值的顺序
代码:
class MinStack {
/** initialize your data structure here. */
Stack<Integer> stack1,stack2;
public MinStack() {
stack1 = new Stack<>();
stack2 = new Stack<>();
}
public void push(int x) {
stack1.add(x);
if (stack2.isEmpty()||stack2.peek()>=x){
stack2.add(x);
}
}
public void pop() {
if (stack1.pop().equals(stack2.peek())){
stack2.pop();
}
}
public int top() {
return stack1.peek();
}
public int min() {
return stack2.peek();
}
}
结果:

336

被折叠的 条评论
为什么被折叠?



