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

Answer:

Can refer to the official problem solution “method three: double pointer/from back to front”.

  1. If you store the last bit of nums1 forward in descending order, you are guaranteed to end up with a properly sorted array with no duplicates.
  2. Use a double pointer to traverse from back to front and exit after iterating through the valid values of any array.
  3. Since NUMs1 has been sorted, after the traversal is completed, it is only necessary to determine whether NUMs2 has completed the traversal.
/ * * *@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 index1 = m - 1; // Used to traverse nums1.
  let index2 = n - 1; // Used to traverse nums2.
  let index = m + n - 1; // Indicates the location where the data is actually stored

  // Use a double pointer to iterate over any valid values of the array and exit.
  while (index1 >= 0 && index2 >= 0) {
    nums1[index--] = nums1[index1] >= nums2[index2] ? nums1[index1--] : nums2[index2--];
  }

  /* * Save the elements not traversed by NUMs2 to nums1 at once. Note the following: * 1. When nums1 completes the loop, index1 is -1, because Index-- is done once before exiting the loop. * 2. Index is the location to store data in the next loop. * 3. If nums2 has been traversed, the remaining nums1 values are sorted and no operation is required. * /
  index1 === -1 && nums1.splice(0, index + 1. nums2.slice(0, index + 1));
};
Copy the code