合并两个有序数组-python

问题描述

leetCode第88题 合并两个有序数组
给你两个按 非递减顺序 排列的整数数组 nums1 和 nums2,另有两个整数 m 和 n ,分别表示 nums1 和 nums2 中的元素数目。
请你 合并 nums2 到 nums1 中,使合并后的数组同样按 非递减顺序 排列。
注意:最终,合并后数组不应由函数返回,而是存储在数组 nums1 中。为了应对这种情况,nums1 的初始长度为 m + n,其中前 m 个元素表示应合并的元素,后 n 个元素为 0 ,应忽略。nums2 的长度为 n 。

示例1:

输入:nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3
输出:[1,2,2,3,5,6]
解释:需要合并 [1,2,3] 和 [2,5,6] 。
合并结果是 [1,2,2,3,5,6] ,其中斜体加粗标注的为 nums1 中的元素。

示例2:

输入:nums1 = [1], m = 1, nums2 = [], n = 0
输出:[1]
解释:需要合并 [1] 和 [] 。
合并结果是 [1] 。

示例3:

输入:nums1 = [0], m = 0, nums2 = [1], n = 1
输出:[1]
解释:需要合并的数组是 [] 和 [1] 。
合并结果是 [1] 。
注意,因为 m = 0 ,所以 nums1 中没有元素。nums1 中仅存的 0 仅仅是为了确保合并结果可以顺利存放到 nums1 中。

提示:

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

进阶:

你可以设计实现一个时间复杂度为 O(m + n) 的算法解决此问题吗?

碰到的问题

问题并不复杂,nums1的总长度为m+n,前m个是nums的元素,后n个元素是0,只要将后n个元素改为nums2的元素,再对nums1进行排序即可。
但我想对我碰到的问题进行一个分享
在这里插入图片描述

## 错误代码 第一版
class Solution:
    def merge(self, nums1: [int], m: int, nums2: [int], n: int) -> None:
        """
        Do not return anything, modify nums1 in-place instead.
        """
        nums1 = nums1[:m]
        nums1 = nums1+nums2
        nums1.sort()
        print(nums1)

在这里插入图片描述
python的print()函数输出列表时会自带一个空格,起初我还认为不是WA,而是presentation error
于是对输出格式进行了更改

## 错误代码 第二版
class Solution:
    def merge(self, nums1: [int], m: int, nums2: [int], n: int) -> None:
        """
        Do not return anything, modify nums1 in-place instead.
        """
        nums1 = nums1[:m]+nums2
        nums1.sort()
        print("[",end="")
        print(",".join(str(x) for x in nums1),end='')
        print("]",end='')

更改后空格确实没了,但还是错误
在这里插入图片描述
在这里插入图片描述
这时我才注意到输出是[1,2,3,0,0,0],可是我将nums1进行输出得到的是正确结果。
我最初以为是nums1.sort()出现了问题,于是改成nums1 = sorted(nums1),并进行测试

class Solution:
    def merge(self, nums1: [int], m: int, nums2: [int], n: int) -> None:
        """
        Do not return anything, modify nums1 in-place instead.
        """
        print(id(nums1))
        nums1 = nums1[:m]+nums2
        print(id(nums1))
        nums1 = sorted(nums1)
        print(id(nums1))

'''
运行结果
2550904029568
2550904029312
2550904029248
'''

查看变量的地址,发现在python中,每次对列表进行 nums1 = ‘’’ 的赋值操作,nums1的地址都会被改变。用sorted(nums1)和nums1.sort()却不会改变nums1的地址。
将nums1 = nums1[:m]+nums2这种写法在本题中是错误的。而应该对m后的元素直接进行变更,而不是将列表合并赋值给nums1。

## 正确代码
class Solution:
    def merge(self, nums1: [int], m: int, nums2: [int], n: int) -> None:
        """
        Do not return anything, modify nums1 in-place instead.
        """
        for i in range(n):
            nums1[m+i] = nums2[i]
        nums1.sort()

算法优化

这种写法确实简单,但效率并不高。题目中说到两个列表是有序的,而将两个列表合并后成为无序表,之后再进行排序这种做法并没有利用好有序表这个条件,所以可以进行优化。
在n1和n2上分别设立一个指针,比较两个数值的大小,将较小的元素存放到一个临时列表,然后移动指针,继续比较。最后把临时列表的值一个一个赋值到n1。
这种方法只把n1和n2遍历了一遍,时间复杂度为O(m+n)

# python3
class Solution:
    def merge(self, nums1: [int], m: int, nums2: [int], n: int) -> None:
        """
        Do not return anything, modify nums1 in-place instead.
        """
        k = m+n
        temp = [0]*k  #临时列表
        n1Index = 0  #定义两个指针
        n2Index = 0
        for i in range(k):
            if n1Index >= m:   #  nums1的元素已经取完,直接把nums2的元素填入
                temp[i] = nums2[n2Index]
                n2Index += 1
            elif n2Index >= n:   #nums2的元素已经取完,直接把nums1的元素填入
                temp[i] = nums1[n1Index]
                n1Index += 1
            elif nums1[n1Index] < nums2[n2Index]:
                temp[i] = nums1[n1Index]
                n1Index += 1
            else:
                temp[i] = nums2[n2Index]
                n2Index += 1
        nums1[:] = temp

在上述做法中,引入了临时列表temp,但在nums1中有几个0元素占用了空间,没有被利用起来。
这意味着可以进行优化,不需要引入临时列表temp。
在两个有序表中,6比3大,那么意味着6应该放在最后一个,之后指针2前移,5比3大,5应该在倒数第二个,2比3小,倒数第三个应该是3,2与2一样大,倒数第四个应该是2.。这样就不必引入临时列表了。
>在这里插入图片描述

class Solution2:
    def merge(self, nums1: [int], m: int, nums2: [int], n: int) -> None:
        """
        Do not return anything, modify nums1 in-place instead.
        """
        k = m + n
        n1Index = m-1
        n2Index = n-1
        for i in range(k-1,-1,-1):
            if n1Index < 0:  #n1已经取完,剩下的空直接填n2
                nums1[i] = nums2[n2Index]
                n2Index -= 1
            elif n2Index < 0: # n2已经取完,n1就不需要变动了
                break
            elif nums1[n1Index] > nums2[n2Index]:
                nums1[i] = nums1[n1Index]
                n1Index -= 1
            else:
                nums1[i] = nums2[n2Index]
                n2Index -= 1
  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

unseven

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值