[] Array merge two ordered arrays without the need to create a new array

It is carried out directly on the basis of the original A merge of the array. It is from the back merge (an array of length m + n), sequentially taking up the maximum discharge.

Do not worry about the original elements of the array A is overwritten, because the analysis of the code, that element should be covered has appeared in the back of the array.

AC Code:

class Solution {
public:
    void merge(int A[], int m, int B[], int n) {
        int i = m-1;
        int j = n-1;
        int index = m+n-1;
        while(i>=0 && j>=0)
        {
            A[index--] = A[i]>B[j] ? A[i--] : B[j--];
        }
        while(j>=0)
        {
            A[index--] = B[j--];
        }
        
    }
};

 

Guess you like

Origin blog.csdn.net/m0_38033475/article/details/92402709