Easy C code . Shifting first and then merging


  • 0
    B
    void merge(int* nums1, int m, int* nums2, int n) {
        
        //shift nums1 by n positions
        for(int i=m-1; i>=0; i--)
        {
            nums1[i+n] = nums1[i];
        }
        int i = n;
        int j = 0;
      
        //now we have n spaces at front of array nums1
        int k = 0;
        while(i<m+n && j<n)
        {
            if(nums1[i] > nums2[j])
            {
                nums1[k] = nums2[j];
                j++;
            }
            else {
                nums1[k] = nums1[i];
                i++;
            }
            
            k++;
            
        }
        while(i<m+n)nums1[k++] = nums1[i++];
        while(j<n)nums1[k++] = nums2[j++];
        
        // for(int x=0;x<m+n;x++)printf("%d*",nums1[x]);
    
    }
    

Log in to reply
 

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