请你设计一个 最小栈 。它提供 push
,pop
,top
操作,并能在常数时间内检索到最小元素的栈。
实现 MinStack
类:
MinStack()
初始化堆栈对象。void push(int val)
将元素val推入堆栈。void pop()
删除堆栈顶部的元素。int top()
获取堆栈顶部的元素。int getMin()
获取堆栈中的最小元素。
LCR 147. 最小栈 - 力扣(LeetCode)
第一遍的代码:
java">class MinStack {Stack<Integer> stack;Stack<Integer> topMin;/** initialize your data structure here. */public MinStack() {stack = new Stack<>();topMin = new Stack<>(); }public void push(int x) {if(stack.isEmpty()){topMin.push(x);stack.push(x);}else{if(x <= topMin.peek()){topMin.push(x);} stack.push(x);}}public void pop() {if(stack.pop() == topMin.peek()){topMin.pop();} }public int top() {return stack.peek();}public int getMin() {return topMin.peek();}
}/*** 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.getMin();*/
发现在
["MinStack","push","push","push","push","pop","getMin","pop","getMin","pop","getMin"]
[[],[512],[-1024],[-1024],[512],[],[],[],[],[],[]]
的用例中出错。
这里的问题是:
-
==
比较的是引用:Integer
是对象类型,==
比较的是对象的引用,而不是值。如果栈中的元素是通过自动装箱(autoboxing)生成的Integer
对象,==
可能会返回false
,即使值相同。 -
推荐使用
equals()
方法:对于对象类型的比较,应该使用equals()
方法来比较值。
java">class MinStack {Stack<Integer> stack;Stack<Integer> topMin;/** initialize your data structure here. */public MinStack() {stack = new Stack<>();topMin = new Stack<>(); }public void push(int x) {if(stack.isEmpty()){topMin.push(x);stack.push(x);}else{if(x <= topMin.peek()){topMin.push(x);}stack.push(x);}}public void pop() {if(stack.pop().equals(topMin.peek())){topMin.pop();} }public int top() {return stack.peek();}public int getMin() {return topMin.peek();}
}