I. Title Description:

Merge nums2 into nums1 to make nums1 an ordered array.

Initialize nums1 and nums2 to m and n, respectively. You can assume that nums1 has a space size equal to m + n so that it has enough space to hold elements from Nums2.

Example 1: Input nums1 = [1,2,3,0,0], m = 3, nums2 = [2,5,6], n = 3 Output: [1,2,2,3,5,6] Nums1 = [1], m = 1, nums2 = [], n = 0 [1] nums1.length == m + n nums2.length == n 0 <= m, n <= 200 1 <= m + n <= 200 -109 <= nums1[i], nums2[i] <= 109Copy the code

Ii. Analysis of Ideas:

  • The easiest way to do this is to put nums2 at the end of nums1 and sort the entire array directly

AC code

/** * @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) { nums1.splice(m, nums1.length - m, ... nums2); nums1.sort((a, b) => a - b); };Copy the code

Four,

  • Of course, there’s more than one way. Here’s the two-pointer method;
var merge = function(nums1, m, nums2, n) {
    let p1 = 0, p2 = 0;
    const sorted = new Array(m + n).fill(0);
    var cur;
    while (p1 < m || p2 < n) {
        if (p1 === m) {
            cur = nums2[p2++];
        } else if (p2 === n) {
            cur = nums1[p1++];
        } else if (nums1[p1] < nums2[p2]) {
            cur = nums1[p1++];
        } else {
            cur = nums2[p2++];
        }
        sorted[p1 + p2 - 1] = cur;
    }
    for (let i = 0; i != m + n; ++i) {
        nums1[i] = sorted[i];
    }
};


Copy the code

For learning reference only

Refer to the topic

  • Force link (LeetCode)