Share my accepted 6 line solution - Java


  • 1
    L

    Use two pointers, i and j to scan A and B from right to left. Each time, put larger element at A[k]. Loop condition: j >= 0 which covers two cases:

    1. All elements in B has been scanned, the rest elements in A are all at right positions

    2. All elements in A has been scanned, copy the rest from B to A.

      public void merge(int A[], int m, int B[], int n) {

      int k = m + n - 1, i = m - 1, j = n - 1;
      while(j >= 0) {
      	if(i >= 0 && A[i] >= B[j])  // i >=0, in case A is empty
      		A[k--] = A[i--];
      	else
      		A[k--] = B[j--];
      }
      

      }


  • 0
    Z

    Hi,in case A is empty,why A[k--] not meet the "java.lang.ArrayIndexOutOfBoundsException"?


Log in to reply
 

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