Short Java solution in 181ms, with only one additional int variable.


  • 0
    J

    Since all the elements in A & B will be merged into A, the last element will be put at p=m+n-1. then just need to merge A & B end first into A, while decreasing pointers p, m, and n in the loop. Only one additional variable, p, is used.

        int p = m + n - 1;
        m--;
        n--;
        while (p >= 0) {
            A[p--] = (m < 0 || (n >= 0 && A[m] < B[n])) ? B[n--] : A[m--];
        }

Log in to reply
 

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