Shortest solution


  • 2
    L

    just merge it backward, note the stop condition is all elements in B is merged to A, so it is 'n > 0' instead of 'i >= 0'.
    another thing is '--m' and 'm' are mix used in one expression, this should be avoid generally, but here, because they are in different part of condition expression, the behavior is as expected.

    void merge(int a[], int m, int b[], int n)
    {
        for( int i = m + n - 1; n > 0; --i )
            a[i] = (m <= 0 || a[m-1] < b[n-1]) ? b[--n] : a[--m];
    }

  • 0
    P

    what happens when Array A size is greater than m+n. It is mentioned in problem statement that A size can be greater than or equal to m+n. You have to all elements beginning from ith position to 0th position. Isn't it?


  • 0
    L

    no, the statement in the problem means: though the actual element count of A is 'm', A has enough capacity to store all elements in both A and B


Log in to reply
 

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