原题链接:https://leetcode-cn.com/problems/merge-sorted-array/
解题思路:
- 创建一个新数组tempArr保存排序后的结果。
- 使用while循环同时遍历两个数组。
- 当nums1[index1] <= nums2[index2]时,将nums1[index1]存入tempArr。
- 当nums2[index2] < nums1[index1]时,将nums2[index2]存入tempArr。
- 完成循环后,查看两个数组是否有未保存的值,若有则继续存入tempArr。
- 将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);
};