Original link: leetcode-cn.com/problems/me…
Implementation idea:
- Create a new array tempArr to hold the sorted results.
- Use the while loop to iterate over both arrays simultaneously.
- When nums1[index1] <= nums2[index2], store nums1[index1] into tempArr.
- When nums2[index2] < nums1[index1], store nums2[index2] into tempArr.
- After completing the loop, store the tempArr values in sequence to 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) {
let tempArr = []; // Cache sorted results
let index1 = 0; // Used to traverse nums1
let index2 = 0; // Used to traverse nums2
// Loop over two arrays
while (index1 < m || index2 < n) {
// Determine the following conditions:
If index2 >= n, nums2 is traversed. In this case, you only need to continue traversing nums1.
Nums1 [index1] <= nums2[index2]; nums1[index1] = nums2[index2];
if (index2 >= n || (index1 < m && nums1[index1] <= nums2[index2])) {
tempArr.push(nums1[index1]);
index1++;
} else if(index1 >= m || (index2 < n && nums2[index2] < nums1[index1])) { tempArr.push(nums2[index2]); index2++; }}// Store sorted results in nums1
for (let i = 0; i < tempArr.length; i++) { nums1[i] = tempArr[i]; }};Copy the code