Simple c++ solution


  • 0
    P
    class Solution {
    public:
        void merge(int a[], int m, int b[], int n) {
            // move all elements of a to end
            int j = m+n-1;
            int i = m-1;
            while(i >= 0) {
                a[j--] = a[i--];
            }
            // start of a
            i = n;
            // start of b
            j = 0;
            
            // sorted array 
            int k = 0;
            while(i < m+n && j < n) {
                if (a[i] > b[j]) {
                    a[k++] = b[j++];
                } else {
                    a[k++] = a[i++];
                }
            }
            while(j < n) {
                a[k++] = b[j++];
            }
            
            while(i < m+n) {
                a[k++] = a[i++];
            }
         }
    };

Log in to reply
 

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