39 lines
1.1 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* https://leetcode.cn/problems/merge-sorted-array/?envType=study-plan-v2&envId=top-interview-150
* @param {number[]} nums1
* @param {number} m
* @param {number[]} nums2
* @param {number} n
* @return {void} Do not return anything, modify nums1 in-place instead.
*/
const merge = function (nums1, m, nums2, n) {
let p1 = m - 1; // 指向nums1的末尾
let p2 = n - 1; // 指向nums2的末尾
let p = m + n - 1; // 指向nums1 填充部分的末尾
while (p1 >= 0 && p2 >= 0) {
if (nums1[p1] > nums2[p2]) {
nums1[p] = nums1[p1];
p1--;
} else {
nums1[p] = nums2[p2];
p2--;
}
p--;
}
// 如果nums2中有未移动的数据全部移动到nums1中
while (p2 >= 0) {
nums1[p] = nums2[p2];
p2--;
p--;
}
};
// 思考如果p1>=0,还需要全部移动一遍吗答案是否定的因为原本就是有序的如果nums2处理完毕之后就表示整个拼接好的nums1
// 就是有序的,只需考虑 p2>=0 的情况
// 其他方法,直接合并两个数组,再对其排序,简单粗暴