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

原题链接: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。
  6. 将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) {
    // 选取两个数组中较小的值存入新数组。
    if (nums1[index1] <= nums2[index2]) {
      tempArr.push(nums1[index1++]);
    } else {
      tempArr.push(nums2[index2++]);
    }
  }


  // 检测哪个数组还有值没有保存,将剩余的值存入新数组。
  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));
  }

  // 将排序后结果存储到nums1
  nums1.splice(0, m + n, ...tempArr);
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值