在做LeetCode的剑指 Offer 30. 包含min函数的栈时
发现
stack.pop() == minstack.peek()
即便是数值相同也不能成立
最后改成
(int)stack.pop() == minstack.peek()
才通过。
个人推测可能是pop()返回值为对象类型,peek()返回的时数值。
参考stack.pop()方法_Java Stack pop()方法与示例_cumtb2009的博客-CSDN博客
对于pop()的返回值说明。
最后附上该题全部代码
class MinStack {
Deque<Integer> stack;
Deque<Integer> minstack;
/** initialize your data structure here. */
public MinStack() {
stack = new LinkedList<Integer>();
minstack = new LinkedList<Integer>();
}
public void push(int x) {
stack.push(x);
if(minstack.isEmpty() || x<=minstack.peek()){
minstack.push(x);
}
}
public void pop() {
// System.out.print(minstack.peek());
// System.out.println(stack.peek());
// System.out.println((int)(stack.peek())==(int)(minstack.peek()));
// int x = stack.pop();
if((int)stack.pop() == minstack.peek()){
minstack.pop();
}
}
public int top() {
return stack.peek();
}
public int min() {
return minstack.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.min();
*/