算法练习:就地(原址)合并两个有序数组【Python】

合并两个有序数组

给定两个有序整数数组 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]
""" 在 nums1 的地址空间合并 nums2 , 不用返回值。
# Testcase:

>>> Solution().merge([1,2,3,0,0,0], 3, [2,5,6], 3)
[1, 2, 2, 3, 5, 6]
"""
class Solution:
    def merge(self, nums1, m, nums2, n):
        """
        Do not return anything, modify nums1 in-place instead.
        使用 归并排序的 merge 过程,nums1 声明为 global ,或者使用 copy  无效;结果判断使用的引用地址
        """
        i,j = 0, 0
        temp = []
        if m>1 and n<=0:
            return nums1
        elif m<=0 and n > 1:
            for i in range(0,n):
                nums1[i] = nums2[i]
        else:
            while i <= m and j < n:
                if nums1[i] <= nums2[j]:
                    if nums1[i] == 0 and i >= m:
                        nums1[i] = nums2[j]
                        j += 1
                        m += 1
                    i += 1
                else:
                    temp = nums1[i:m]
                    nums1[i] = nums2[j]
                    j += 1
                    i += 1
                    m += 1
                    nums1[i:m] = temp
            if j < n:
                nums1.extend(nums2[j:n])
        # 原题不要求返回值,为便于测试只打印
        print(nums1)
        
if __name__ == "__main__":
    import doctest
    doctest.testmod(verbose=True)
Trying:
    Solution().merge([1,2,3,0,0,0], 3, [2,5,6], 3)
Expecting:
    [1, 2, 2, 3, 5, 6]
ok
2 items had no tests:
    __main__.Solution
    __main__.Solution.merge
1 items passed all tests:
   1 tests in __main__
1 tests in 3 items.
1 passed and 0 failed.
Test passed.

题解:

对于有序列表的合并,最直接用归并排序的合并过程,但是该题要求在 nums1 地址空间合并,就需要考虑到 python 变量值引用的问题,也推测不希望有额外的空间;
那么结合题意,可以选择插入排序,不同的是在替换元素的过程中 nums1 的长度 m 是要扩张的,占位符为"0"。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值