leetcode88.合并两个有序数组(简单题!)

思路:合并两个数组,再进行排序(利用快速排序)

class Solution(object):
    def quicksort(self, num, i, j):
        if i>=j: # 跳出循环的条件要出来
            return 
        left = i
        right = j
        temp = num[i]
        while left < right:
            while left < right and temp <= num[right]:
                right -= 1
            num[left] = num[right]
            while left < right and temp >= num[left]:
                left += 1
            num[right] = num[left]
        num[left] = temp
        self.quicksort(num,i,left-1)
        self.quicksort(num,left+1,j)

    def merge(self, nums1, m, nums2, n):
        """
        :type nums1: List[int]
        :type m: int
        :type nums2: List[int]
        :type n: int
        :rtype: None Do not return anything, modify nums1 in-place instead.
        """
        nums1[m:] = nums2
        # 法一 利用用快速排序
        self.quicksort(nums1,0,len(nums1)-1)
        # return nums1

        # 法二 直接调用函数sort()
        # nums1.sort()

时间复杂度:O((m+n)log(m+n))

空间复杂度:最坏情况下O(m+n)    # 每层树每个节点都开辟空间来算的话是这样  ?? ??但是这里一般按照O(log(m+n))因为递归树有log(m+n)层。

快速排序的空间复杂度分析

快速排序的空间复杂度由以下两部分组成:

  1. 递归栈空间:这部分空间用来保存每次递归调用时的函数参数、局部变量和返回地址等信息。

  2. 临时空间:这部分通常是用于存储在排序过程中临时需要的变量,但在经典的快速排序实现中,这部分空间是常数级的。其实不用考虑这部分了。

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值