chencl1986 / Blog

Welcome to lee's blog.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

LeetCode题解:88. 合并两个有序数组,双指针+从前往后+使用新数组Copy,JavaScript,详细注释

chencl1986 opened this issue · comments

原题链接:https://leetcode-cn.com/problems/merge-sorted-array/

实现思路:

  1. 创建一个新数组tempArr保存排序后的结果。
  2. 使用while循环同时遍历两个数组。
  3. 当nums1[index1] <= nums2[index2]时,将nums1[index1]存入tempArr。
  4. 当nums2[index2] < nums1[index1]时,将nums2[index2]存入tempArr。
  5. 完成循环后,将tempArr的值依次存入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 = []; // 用于缓存排序后结果
  let index1 = 0; // 用于遍历nums1
  let index2 = 0; // 用于遍历nums2

  // 循环遍历两个数组
  while (index1 < m || index2 < n) {
    // 判断条件如下:
    // 1. index2 >= n时,表示nums2已经遍历完成,此时只需要继续遍历nums1。
    // 2. nums1[index1] <= nums2[index2]的时候,将nums1[index1]存储到tempArr中,这里要特别注意判断index1 < m,保证用于判断的nums1[index1]是有值的。
    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++;
    }
  }

  // 将排序后结果存储到nums1
  for (let i = 0; i < tempArr.length; i++) {
    nums1[i] = tempArr[i];
  }
};