LeetCode.88.合并两个有序数组

给定两个有序整数数组 nums1 和 nums2,将 nums2 合并到 nums1 中,使得 num1 成为一个有序数组。

说明:

初始化 nums1 和 nums2 的元素数量分别为 m 和 n。
你可以假设 nums1 有足够的空间(空间大小大于或等于 m + n)来保存 nums2 中的元素。

示例:

输入:
nums1 = [1,2,3,0,0,0], m = 3
nums2 = [2,5,6],       n = 3

输出: [1,2,2,3,5,6]

思路1:

将nums2中的元素简单加到nums1后,排序即可。

代码1:

class Solution:
    def merge(self, nums1, m, nums2, n):
        """
        :type nums1: List[int]
        :type m: int
        :type nums2: List[int]
        :type n: int
        :rtype: void Do not return anything, modify nums1 in-place instead.
        """
        while n-1>=0:
            nums1[m]=nums2[n-1]
            n-=1
            m+=1
        nums1.sort()

分析1:

时间复杂度O(m(m+n)log(m+n)),空间复杂度O(0)

思路2:

由于合并后A数组的大小必定是m+n,所以从最后面开始往前赋值,先比较A和B中最后一个元素的大小,把较大的那个插入到m+n-1的位置上,再依次向前推。如果A中所有的元素都比B小,那么前m个还是A原来的内容,没有改变。如果A中的数组有比B大的,当A循环完了,B中还有元素没加入A,直接用个循环把B中所有的元素覆盖到A剩下的位置。

代码2:

class Solution:
    def merge(self, nums1, m, nums2, n):
        """
        :type nums1: List[int]
        :type m: int
        :type nums2: List[int]
        :type n: int
        :rtype: void Do not return anything, modify nums1 in-place instead.
        """
        count=m+n-1
        m-=1
        n-=1
        while m>=0 and n>=0:
            if nums1[m]>nums2[n]:
                nums1[count]=nums1[m]
                m-=1
            else:
                nums1[count]=nums2[n]
                n-=1
            count-=1
        while n>=0:
            nums1[count]=nums2[n]
            count-=1
            n-=1

分析2:

时间复杂度O(N+M),空间复杂度O(0)

猜你喜欢

转载自blog.csdn.net/u013942370/article/details/82822232
今日推荐