Merge Sorted Array - LeetCode

https://leetcode.com/problems/merge-sorted-array/?envType=study-plan-v2&envId=top-interview-150

LeetCode_Sharing.png

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 1:

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.

Example 2:

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].

Example 3:

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

Follow up: Can you come up with an algorithm that runs in O(m + n) time?

有时候while比for写出来逻辑性更强,特别是使用类似指针的方式。

class Solution:
    def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
        """
        Do not return anything, modify nums1 in-place instead.
        """
        p1 = len(nums1) - 1
        p2 = len(nums2) - 1

        while p1 >= 0 and p2 >= 0:
            if nums1[p1] == 0:
                nums1[p1] = nums2[p2]
                p1 -= 1
                p2 -= 1
            else:
                p1 -=1

        nums1.sort()
class Solution:
    def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
        """
        Do not return anything, modify nums1 in-place instead.
        """
        p1 = m - 1
        p2 = n - 1
        p3 = m + n - 1

        while p1 >= 0 and p2 >= 0:
            if nums1[p1] > nums2[p2]:
                nums1[p3] = nums1[p1]
                p1 -= 1
            else:
                nums1[p3] = nums2[p2]
                p2 -= 1
            p3 -= 1

        while p2 >= 0:
            nums1[p3] = nums2[p2]
            p2 -= 1
            p3 -= 1

第一种方法用了sort,不是很好,方法2显然是更好的解法。

class Solution {
    public void merge(int[] nums1, int m, int[] nums2, int n) {
        int p1 = m - 1;
        int p2 = n - 1;
        int p3 = m + n - 1;

        while (p1 >= 0 && p2 >= 0){
            if (nums1[p1] > nums2[p2]){
                nums1[p3] = nums1[p1];
                p1--;
            }
            else {
                nums1[p3] = nums2[p2];
                p2--;
            }
            p3--;
        }
        while(p2 >= 0){
            nums1[p3] = nums2[p2];
            p2--;
            p3--;
        }
    }
}
class Solution {
public:
    void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
        int p1 = m - 1;
        int p2 = n - 1;
        int p3 = m + n - 1;

        while (p1 >= 0 && p2 >= 0){
            if (nums1[p1] > nums2[p2]){
                nums1[p3] = nums1[p1];
                p1--;
            } else{
                nums1[p3] = nums2[p2];
                p2--;
            }
            p3--;
        }
        while (p2 >= 0){
            nums1[p3] = nums2[p2];
            p2--;
            p3--;
        }
    }
};

Merge Sorted Array问题概述:

问题

给定两个已排序的整数数组nums1nums2,以及它们的元素数量mn。你的任务是将nums2合并到nums1中,使得nums1成为一个已排序的数组。不应该返回合并后的数组,而是直接修改nums1数组。

注意

为了简化问题,nums1的长度等于m + n,其中前m个元素代表应合并的元素,其余的元素都是0。而nums2的长度则是n

解决策略:

  1. 双指针法 - 从后往前合并
    • 最简单的思路是先合并,再排序。但这种做法不够高效,因为它没有利用到nums1nums2都是有序的特点。
    • 我们可以使用双指针法从后往前合并。这样做的好处是在nums1的后部分已经是空的,我们可以直接在那里放置合并后的结果,不会影响到nums1的其他部分。
    • 具体来说,我们分别为nums1nums2设置一个指针,初始位置为m-1n-1,然后比较这两个指针指向的值,把较大的值放到m+n-1的位置上,然后移动指针和目标位置。
    • 这种方法的时间复杂度是O(m+n),因为每个元素只被处理一次。
  2. 先合并,再排序
    • 这种方法简单直观,但它的时间复杂度较高,为O((m+n)log(m+n)),因为需要对整个数组进行排序。

总结:

Merge Sorted Array问题是合并两个有序数组的经典问题,考察了数组操作和双指针技巧。从后往前的双指针方法是一个非常高效的解法,充分利用了两个输入数组的已排序特点。