3 while loops and 6ms

  • 0

    This is the cleanest code I came up with:

        void merge(int A[], int m, int B[], int n) {
        int i=m-1, j=n-1, k=m+n-1;
        while (j>=0) {
            while (i >= 0 &&  A[i] >  B[j]        ) A[k--] = A[i--];
            while (j >= 0 && (A[i] <= B[j] || i<0)) A[k--] = B[j--];

    Asymmetry in the two inner while loops is caused by additional condition i<0 which keep the B=>A copying going if A ran out of elements.

Log in to reply

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