Input: nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3 Output: [1,2,2,3,5,6] Explanation: The arrays we are merging are [1,2,3] and [2,5,6]. The result of the merge is [1,2,2,3,5,6] with the underlined elements coming from nums1.
Example 2:
1 2 3 4
Input: nums1 = [1], m = 1, nums2 = [], n = 0 Output: [1] Explanation: The arrays we are merging are [1] and []. The result of the merge is [1].
Example 3:
1 2 3 4 5
Input: nums1 = [0], m = 0, nums2 = [1], n = 1 Output: [1] Explanation: The arrays we are merging are [] and [1]. The result of the merge is [1]. Note that because m = 0, there are no elements in nums1. The 0 is only there to ensure the merge result can fit in nums1.
/** * @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) { m -= 1; n -= 1 for (let i = nums1.length -1; i >= 0; i--) {
// 如果這次比較 nums1 比 nums2 大,那就把 nums1 當前 index 的 element 取出來然後塞入 nums1 的當前 index if ( m > -1 && nums1[m] >= nums2[n]) { nums1[i] = nums1[m]; m -= 1;
// 如果這次比較 nums2 比 nums1 大,那就把 nums2 當前 index 的 element 取出來然後塞入 nums1 的當前 index ,然後把 nums1 放進 nums2 原來的位置 } elseif (n > -1) { nums1[i] = nums2[n]; n -= 1; } } };