LeetCode----Merge Sorted Array

本文探讨了如何使用Python合并两个已排序的整数数组,提供了两种不同的解决方案,并讨论了在不返回任何值的情况下直接修改第一个数组以保持排序的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Merge Sorted Array

 

Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.

Note:
You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2. The number of elements initialized in nums1 and nums2 are m and n respectively.


分析:

合并两个已经有序的数组,本来是按归并排序中合并子数组的思路来,用Python写的,提交一直不对,后来发现题目要求是排序后nums1被修改了,即在函数运行后,nums1保存修改的结果。想了一下,Python并没有类似C++的引用,以为需要换种语言实现了。但是,查看了Discuss后发现居然有人是用Python提交的,原来我忘了Python中的赋值以及拷贝的东西了,有一篇博客可以好好学习一下。以后有时间还是多看看Dicuss里的东西,里面总有一些实现优雅简短的代码出现。


代码1:

class Solution(object):
    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.
        """
        i = j = 0
        while i < (m+j) and j < n:
            if nums2[j] <= nums1[i]:
                nums1.insert(i, nums2[j])
                j += 1
                i += 1
            else:
                i += 1
        nums1[m+j:] = nums2[j:]
        nums1[:] = nums1[: m+n]
        print nums1


代码2:

class Solution(object):
    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.
        """
        nums1[m:] = nums2[:n]
        nums1.sort()





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值