Anyone tell me why my java code got wrong answer?


  • 0
    G

    My code is as follows:

    Stack<Integer> st = new Stack<Integer>();
        Stack<Integer> min = new Stack<Integer>();
        public void push(int x) {
            if(st.isEmpty() || (!min.isEmpty() && min.peek()>=x)){
                min.push(x);
            }
            st.push(x);
        }
        public void pop() {
            if(st.peek() == min.peek())
                min.pop();
            st.pop();
        }
    
        public int top() {
            return st.peek();
        }
    
        public int getMin() {
            return min.peek();
        }
    

    I got wrong answer with

    >     Input: push(512),push(-1024),push(-1024),push(512),pop,getMin,pop,getMin,pop,getMin
    >     Output: [-1024,-1024,-1024] 
    >     Expected: [-1024,-1024,512]
    

    If I change the if in pop() function from

    if(st.peek() == min.peek())

    to

    if(st.peek() <= min.peek())

    My code got accepted. Can anyone tell me what's the problem here?


  • 3
    E

    The problem is here: st.peek() == min.peek()

    The return types for both of the stacks are Integer, which are objects rather then primitives. == in this case check whether the two objects are the same object. Although they have the same value, they are different instances. The expression will still be evaluated to false.

    Modify you code to st.peek().intValue() == min.peek().intValue()


  • 0
    G

    That makes a lot of sense. Thank you so much.


Log in to reply
 

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