Java using two Stacks: What's wrong with this code?


  • 0

    Stack<Integer> s = new Stack<Integer>();
    Stack<Integer> ms = new Stack<Integer>();

    public void push(int x) {
        s.push(x);
        if(ms.isEmpty() || ms.peek().intValue() >= x) 
            ms.push(x);
    }
    
    public void pop() {
        if(ms.peek().intValue() == s.pop().intValue())
        	ms.pop();
    }
    
    public int top() {
        return s.peek().intValue();
    }
    
    public int getMin() {
        return ms.peek().intValue();
    }
    

    The auto-grader said wrong answer for input "512, -1024, -1024, 512", I can't figure out why. Any idea?


  • 0
    R

    I have a similar issue, seems to fail the case but the answers are definitely in correct.


  • 0

    That doesn't get "wrong answer". It gets "compile error".


  • 0

    Where's the compile error? I didn't get one, just "wrong answer" by the auto-grader.


  • 0

    Line 6: error: bad operand types for binary operator '>='

    And that's not surprising, since a Stack holds objects of arbitrary type, which you can't just compare to ints.


  • 0

    OK, thank you sir, I've got ur point. But I think Java does the auto-unboxing of primitive objects? Since this piece of codes didn't turn out to be compile error on both my Eclipse and leetcode OJ. Anyway, as per your request, I'll add "intValue( )" to all objects to this code, but it still won't lead to the right answers.....thx anyway


  • 0

    I'm pretty sure you need Stack<Integer> for the auto(un)boxing, not just Stack. I'm also pretty sure the LeetCode OJ wouldn't give us such different results like you claim it did. I strongly believe you did not submit the code you showed us.


  • 0
    L

    Hi @StefanPochmann ,could you please do me a favor to figure out what's going wrong with my code? The url is https://leetcode.com/discuss/53252/help-figure-get-time-limit-exceeded-when-one-line-code-omited

    Thank you so much!


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.