Runs OK in my IDE but Got Wrong Answer on LeetCode


  • 0
    H

    The input was [1,1,1,2], LeetCode says my result was [1,1,1] while expected result should be [1,1,2].
    However, I got [1,1,2] on my local ide, not sure what's wrong, anyone can help? Thanks in advance.

    I was trying to add every element in A to a list, except those appears more than twice. And convert the list to array A, return size of the list.

    public int removeDuplicates(int[] A) {
            if(A.length<3){
                return A.length;
            }
            int count = 1;
            List<Integer> AList = new ArrayList<>();
            AList.add(A[0]);
            for(int i=1;i<A.length;i+=1){    	
                if(A[i]==A[i-1]){
                    count += 1;
                }else{
                    count = 1;
                }
                if(count < 3){
                    AList.add(A[i]);
                }
            }
            A = new int[AList.size()];
            for(int i=0;i<A.length;i+=1){
                A[i] = AList.get(i);
            }
            return AList.size();
        }

  • 1
    L

    I think that is because you use new storage place for array A by using codes like:

    A = new int[AList.size()];
    

    Leetcode OJ requires you to change the value at original storage place of A


  • 0
    H

    Ah, you are right. I commented out "A = new int[AList.size()];" and change the next line
    for(int i=0;i<A.length;i+=1){ to
    for(int i=0;i<AList.size();i+=1){
    and it works!


Log in to reply
 

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