[路飞]_每天刷leetcode_69(合并两个有序数组 Merge sortd array)

257 阅读2分钟

「这是我参与2022首次更文挑战的第30天,活动详情查看:2022首次更文挑战

合并两个有序数组 Merge sortd array

LeetCode传送门88. 合并两个有序数组

题目

给你两个按 非递减顺序 排列的整数数组 nums1 和 nums2,另有两个整数 m 和 n ,分别表示 nums1 和 nums2 中的元素数目。

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

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

You are given two integer arrays nums1 and nums2, sorted in non-decreasing order, and two integers m and n, representing the number of elements in nums1 and nums2 respectively.

Merge nums1 and nums2 into a single array sorted in non-decreasing order.

The final sorted array should not be returned by the function, but instead be stored inside the array nums1. To accommodate this, nums1 has a length of m + n, where the first m elements denote the elements that should be merged, and the last n elements are set to 0 and should be ignored. nums2 has a length of n.

Example:


Input: nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3
Output: [1,2,2,3,5,6]
Explanation: The arrays we are merging are [1,2,3] and [2,5,6].
The result of the merge is [1,2,2,3,5,6] with the underlined elements coming from nums1.

Input: nums1 = [1], m = 1, nums2 = [], n = 0
Output: [1]
Explanation: The arrays we are merging are [1] and [].
The result of the merge is [1].

Input: nums1 = [0], m = 0, nums2 = [1], n = 1
Output: [1]
Explanation: The arrays we are merging are [] and [1].
The result of the merge is [1].
Note that because m = 0, there are no elements in nums1. The 0 is only there to ensure the merge result can fit in nums1.

Constraints:

  • nums1.length == m + n
  • nums2.length == n
  • 0 <= m, n <= 200
  • 1 <= m + n <= 200
  • 109<=nums1[i],nums2[j]<=109-10^9 <= nums1[i], nums2[j] <= 10^9

思考线


解题思路

我们知道nums1的数组是多出来n个长度的,我们可以根据两个数组的有序性,比较数组的尾部,把最大的放到最后面,以此类推,进行n+m步操作即可得到排序后的数组。

这里有个问题,我们如何确定这样的操作不会覆盖掉nums1中的值呢?

在这里我们想象一下,如果nums2的值为空,那么nums1也就不需要变动所以这种情况下可以得到正确的结果。

nums2有值,我们想象一下,最可能出现覆盖值的情况是,大的数字全部是nums2,小的数子全部在nums1内,这种情况直接把num2从下标为m的位置复制过去即可,也不会出现覆盖掉nums1中的值的情况,综上,我们可以大胆地使用这种方法来解题。

解题代码如下:

/**
 Do not return anything, modify nums1 in-place instead.
 */
function merge(nums1: number[], m: number, nums2: number[], n: number): void {
    let len = m + n;
    let p1 = m - 1, p2 = n - 1;
    for (let i = len - 1; i >= 0; i--) {
        if (p1 >= 0 && p2 >= 0 && (nums1[p1] > nums2[p2]) || p2 < 0) {
            nums1[i] = nums1[p1]
            p1--
        } else {
            nums1[i] = nums2[p2]
            p2--
        }

    }
};

时间复杂度

O(m + n): 进行了m+n次遍历

这就是我对本题的解法,如果有疑问或者更好的解答方式,欢迎留言互动。