Skip to content
Home » X Algorithm – 250 LeetCode Coding Challenge Questions » Page 3

X Algorithm – 250 LeetCode Coding Challenge Questions

Merge Sorted Array

This is an elegant way to make it in O(m+n) from leetcode discussion sktlez.

/**
 * @param {number[]} nums1
 * @param {number} m
 * @param {number[]} nums2
 * @param {number} n
 * @return {void} Do not return anything, modify nums1 in-place instead.
 */
var merge = function(nums1, m, nums2, n) {
    let insInd = nums1.length - 1; //Position to start inserting into nums1 array
    let i = m - 1; //index to the end of nums1 array (right before the 0's start)
    let j = nums2.length - 1; //index to the end of nums2 array

    //Merge the arrays
    while(j >= 0 && i >= 0) {
        if (nums2[j] >= nums1[i]) {
            nums1[insInd--] = nums2[j--];
        } else {
            nums1[insInd--] = nums1[i--];
        }
    }

    //Copy over any remaining elements
    while (i >= 0) {
        nums1[insInd--] = nums1[i--];
    }

    //Copy over any remaining elements
    while (j >= 0) {
        nums1[insInd--] = nums2[j--];
    }
};

Leave a Reply

Your email address will not be published.

Pages: 1 2 3 4