Merge Sorted Array

地址:点击打开链接

算法要求合并两个有序数组,其中将数组二的元素合并到数组1中,数据结构书中合并有序数组是新建一个数组,然后依次比较大小,这个题如果按照这种思路,明显时间复杂度是o(n*n),所以有一个简单的方法,从尾部开始比较,因为数组1的长度足够,所以设计从两个数相加的长度开始比较即可

不知道什么原因python的代码一直通不过,我写了个java的反倒过了


答案:

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

        if n > 0 and m:
            len1 = m - 1
            len2 = n - 1
            total = m + n - 1
            while len2 >= 0 and len1 >= 0:
                if nums1[len1] >= nums2[len2]:
                    nums1[total] = nums1[len1]
                    len1 -= 1
                    total -= 1
                else:
                    nums1[total] = nums2[len2]
                    len2 -= 1
                    total -= 1
             while len2 >= 0:
                        nums1[len2] = nums2[len2]
                        len2 -= 1
        elif n > 0 and not m:
            nums1 = nums2
        else:
            pass


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值