Merge Sorted Arrays

Merge Sorted Arrays

- 2 mins

88. Merge Sorted Array

Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.

Note:

  1. The number of elements initialized in nums1 and nums2 are m and n respectively.
  2. You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2.
   Example:

   Input: 
   nums1 = [1,2,3,0,0,0], m = 3
   nums2 = [2,5,6],       n = 3

   Output: [1,2,2,3,5,6]

1. First Solution

    const merge = function (nums1, m, nums2, n) {
        let first = m - 1;
        let second = n - 1;

        for (let i = m + n - 1; i >= 0; i--) {
            if (second < 0) {
                break;
            }

            if (nums1[first] > nums2[second]) {
                nums1[i] = nums1[first];
                first--;
            } else { 
                nums1[i] = nums2[second];
                second--;
            }
        }
    };

2. Second Solution

Approach:


    const merge = function (nums1, m, nums2, n) {
        let final = m + n - 1;
        m--;
        n--;

        while (m >= 0 || n >= 0) {
            // if no more nums2 then just copy remaining m elements
            if (n < 0 || nums1[m] > nums2[n]) {
                nums1[final] = nums1[m];
                m--;
            } else { // m < 0 || nums1[m] < nums2[n]
                nums1[final] = nums2[n];
                n--;
            }
            final--;
        }

        return nums1;
    };

Merge Sorted Arrays

Albiona Hoti

Albiona Hoti

comments powered by Disqus
rss facebook twitter github gitlab youtube mail spotify lastfm instagram linkedin google google-plus pinterest medium vimeo stackoverflow reddit quora quora