问答

当前位置

Min Stack 请教一个问题

  • Ta: 杜承澔

想问一下为什么我的代码无法通过下面的test case呢? 感觉逻辑是对的。 请指教,多谢

Input
["MinStack","push","push","push","push","pop","getMin","pop","getMin","pop","getMin"]
[[],[512],[-1024],[-1024],[512],[],[],[],[],[],[]]
Output
[null,null,null,null,null,null,-1024,null,-1024,null,-1024]
Expected
[null,null,null,null,null,null,-1024,null,-1024,null,512]
class MinStack {
    Stack<Integer> stack;
    Stack<Integer> minStack;
    /** initialize your data structure here. */
    public MinStack() {
        stack = new Stack<>();
        minStack = new Stack<>();
    }

    public void push(int x) {
        stack.push(x);
        if (minStack.isEmpty() || (!minStack.isEmpty() && x <= minStack.peek())) {
            minStack.push(x);
        }
    }

    public void pop() {
        if (!minStack.isEmpty() && stack.peek() == minStack.peek()) {
             minStack.pop();  
             stack.pop();
        } else {
            stack.pop();
        }
    }

    public int top() {
        if (!stack.isEmpty()) {
            return stack.peek();
        }
        return -1;
    }

    public int getMin() {
        if (!minStack.isEmpty()) {
            return minStack.peek();
        }
        return -1;
    }
}

/**
 * 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();
 */

1 个回复

2019-09-20 serenity

if (!minStack.isEmpty() && stack.peek() == minStack.peek()) 这里的“==”换成.equals()就好

我来回答

您没有权限

为提高问答质量,问答版块发言权限只向九章学员开放

登录 注册

© Jiu Zhang 2013-. All rights reserved. 京ICP备16004690号-1