Cleanest Solution


  • 22
    B
    class Solution {
    public:
        void merge(int A[], int m, int B[], int n) {
            int i = m-1;
            int j = n-1;
            for (int k = m+n-1; k >= 0; k--) {
                if (i < 0)              A[k] = B[j--];
                else if (j < 0)         A[k] = A[i--];
                else if (A[i] < B[j])   A[k] = B[j--];
                else                    A[k] = A[i--];
            }
        }
    };

  • 0
    W

    really clean code.
    but this is wrong when A's size is really large than m+n, for example,
    A={1,2,3, , } B = {4};
    A would end up like this A ={1,1,2,3,4}.


  • 0
    D

    if A={1,2,3,,},B={4},we get m=3,n=1. so k start at m+n-1=3.it seems like A would end up with A={1,2,3,4}. am I wrong?


  • 1
    M

    When j < 0, it's no need to update the array, just break the for loop.


Log in to reply
 

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