Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
chencl1986 opened this issue Aug 15, 2020 · 0 comments

Comments

@chencl1986
Copy link
Owner

原题链接: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);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant