Fastest solution ? Even squeezed an add operation

  • 0
    void merge(int A[], int m, int B[], int n) {
        	// Copy the bigger one from the end of A or B into the end of buffer until reaching to the begining of B (or A handled inside the loop)
        	for (int *pa = A + m - 1, *pb = B + n - 1, *pe = A + m + n - 1; pb >= B;){
        		*pe-- = *pa > *pb ? *pa-- : *pb--;
        		if ( pa < A ) {
                    // Reaching begining of A, direct copy the rest of B, if any
        		    // This line is easy to undrestand, but need an extra add operation
        		    //memcpy(A, B, (pb-B+1)*sizeof(int));
                    // Make use of pa is effective pointing to A[-1], and out of bound
        		    memcpy(A, B, (pe-pa)*sizeof(int));

Log in to reply

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