Original link: leetcode-cn.com/problems/me…

Answer:

  1. Create a new array tempArr to hold the sorted results.
  2. Use the while loop to iterate over both arrays simultaneously.
  3. When nums1[index1] <= nums2[index2], store nums1[index1] into tempArr.
  4. When nums2[index2] < nums1[index1], store nums2[index2] into tempArr.
  5. After the loop is complete, check to see if there are any unsaved values in both arrays, and continue saving to tempArr if there are.
  6. 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.

  // Use a double pointer to iterate over any valid values of the array and exit.
  while (index1 < m && index2 < n) {
    // Take the smaller value of the two arrays and store it in the new array.
    if (nums1[index1] <= nums2[index2]) {
      tempArr.push(nums1[index1++]);
    } else{ tempArr.push(nums2[index2++]); }}// Check which array has unsaved values and store the remaining values in the new array.
  if(index1 < m) { tempArr.splice(index1 + n, m - index1, ... nums1.slice(index1, m)); }if(index2 < n) { tempArr.splice(index2 + m, n - index2, ... nums2.slice(index2, n)); }// Store sorted results in nums1
  nums1.splice(0, m + n, ... tempArr); };Copy the code