1 题目
定义栈的数据结构,请在该类型中实现一个能够得到栈的最小元素的 min 函数在该栈中,调用 min、push 及 pop 的时间复杂度都是 O(1)。
示例:
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.min(); --> 返回 -3.
minStack.pop();
minStack.top(); --> 返回 0.
minStack.min(); --> 返回 -2.
提示:
各函数的调用总次数不超过 20000 次
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/bao-han-minhan-shu-de-zhan-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
2 Java
2.1 方法一(辅助栈,单调栈)
辅助变量必须是栈,不能是int
注意空栈pop需要抛出Exception
throw new RuntimeException(“栈中元素为空,此操作非法”);
pop中注释的写法有问题
两个 peek 比较的是两个Integer,== 比较的就是地址,需要用equals
报错如下
输入:
[“MinStack”,“push”,“push”,“push”,“push”,“pop”,“min”,“pop”,“min”,“pop”,“min”]
[[],[512],[-1024],[-1024],[512],[],[],[],[],[],[]]
输出
[null,null,null,null,null,null,-1024,null,-1024,null,-1024]
预期结果
[null,null,null,null,null,null,-1024,null,-1024,null,512]
class MinStack {
Stack<Integer> A;
Stack<Integer> B;
/** initialize your data structure here. */
public MinStack() {
A = new Stack<Integer>();
B = new Stack<Integer>();
}
public void push(int x) {
if(B.isEmpty() || x <= B.peek()) B.push(x);
A.push(x);
}
public void pop() {
if(!A.isEmpty() && !B.isEmpty()){
int top = A.pop();
if(top == B.peek()) B.pop(); // !top 是 int 类型,导致 peek 自动拆箱了
// if(A.peek() == B.peek()) B.pop(); // !!!错误,两个 peek 比较的是两个Integer,== 比较的就是地址,需要用equals
// A.pop();
}
}
public int top() {
if(!A.isEmpty()) return A.peek();
throw new RuntimeException("栈中元素为空,此操作非法");
}
public int min() {
if(!B.isEmpty()) return B.peek();
throw new RuntimeException("栈中元素为空,此操作非法");
}
}
/**
* 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();
*/