Skip to content
本页目录

88.合并两个有序数组

题目描述

  • 给你两个按 非递减顺序 排列的整数数组 nums1nums2,另有两个整数 mn ,分别表示 nums1nums2 中的元素数目。

  • 请你 合并 nums2nums1 中,使合并后的数组同样按 非递减顺序 排列。

注意

注意:最终,合并后数组不应由函数返回,而是存储在数组 nums1 中。为了应对这种情况,nums1 的初始长度为 m + n,其中前 m 个元素表示应合并的元素,后 n 个元素为 0 ,应忽略。nums2 的长度为 n 。

示例

输入:nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3 输出:[1,2,2,3,5,6] 解释:需要合并 [1,2,3][2,5,6] 。 合并结果是 [1,2,2,3,5,6] ,其中斜体加粗标注的为 nums1 中的元素。

思路

  • 先定义三个指针

    • index1 指向 nums1 最后一个 非 0 的位置
    • index2 指向 nums2 最后一个位置
    • tail 指向 nums1 最后一个位置
  • 比较大小 把大的元素插入 nums1[tail]

  • 把剩余的 nums2 中的元素插入

  • 注意:剩余的 nums1 中的元素可以不用处理,因为本来的位置就是对的

代码

js
/**
 * @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) {
  // 先定义三个指针
  // index1 指向 nums1 最后一个 非 0 的位置
  // index2 指向 nums2 最后一个位置
  // tail 指向 nums1 最后一个位置
  let index1 = m - 1,
    index2 = n - 1,
    tail = m + n - 1;
  // 比较大小 插入 nums1[tail]
  while (index1 >= 0 && index2 >= 0) {
    if (nums1[index1] > nums2[index2]) {
      nums1[tail] = nums1[index1];
      index1--;
    } else {
      nums1[tail] = nums2[index2];
      index2--;
    }
    tail--;
  }
  // 把剩余的 nums2 中的元素插入
  while (index2 >= 0) {
    nums1[tail] = nums2[index2];
    index2--;
    tail--;
  }
  return nums1;
};

let nums1 = [1, 2, 3, 0, 0, 0],
  m = 3,
  nums2 = [2, 5, 6],
  n = 3;

console.log(merge(nums1, m, nums2, n)); //[ 1, 2, 2, 3, 5, 6 ]

MIT Licensed