Strange that I can even get Wrong Answer (input:[],[1])


  • 0
    R

    I tried the first time and found that this problem already occurred, so I wrote some extra code to mitigate this problem by adding if(m==0). But it does not seem to work, why?

    public void merge(int A[], int m, int B[], int n) {
            if(m==0){
                A = B;
            } else {
                int[] result = new int[A.length];
                int a=0;
                int b=0;
                int i=0;
                while(a<m && b<n && i<(m+n)){
                    if(A[a]>B[b]){
                        result[i] = B[b];
                        i++;
                        b++;
                    } else {
                        result[i] = A[a];
                        i++;
                        a++;
                    }
                }
            
                if(i==(m+n))
                A = result;
            
                if(a==m){
                    while(i<(m+n)){
                        result[i] = B[b];
                        i++;
                        b++;
                    }
                } else {
                    while(i<(m+n)){
                        result[i] = A[a];
                        i++;
                        a++;
                    }
                }
                A = result;
            }
        } 
    

    Thanks in advance.


  • 2
    M

    The line A=B redirects the variable A to point to B instead of the array outside of the method. Because of that, the array outside the method does not change. You need to change the line to just copy the contents, not the array itself.

     for i in range (0, len(B)):
        A[i] = B[i]; 

  • 0
    R

    Thank you! I fixed the code per your suggestion and it worked.


Log in to reply
 

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