leetcode-求数组中第K大的数(快排)

question:
在这里插入图片描述

解法:求这种最大最小的数或者数组,一般都会先将他们进行排序,这里我还是采用快排,之后会更新其他排序方法


程序1:运行时出现了超时,因为时间复杂度已经达到了两次方,很高的时间复杂度系统不能通过

class Solution:
    def findKthLargest(self, nums: List[int], k: int) -> int:
    	def findTopKth(left, right):
            indx = random.randint(left, right)
            nums[left], nums[indx] = nums[indx], nums[left]
            base = nums[left]
            i = left
            j = right
            
           # 时间复杂度较高,暂时不知道怎么去改变,大家可以给点建议
            **while i<j:
                while i<j and base >= nums[j]:
                    j -= 1
                nums[i] = nums[j]
                while i<j and base >= nums[i]:
                    i -= 1
                nums[j] = nums[i]               
            nums[left], nums[i] = nums[i], nums[left]**

            if i == k - 1:
                return nums[i]
            elif i > k - 1:
                return findTopKth(left, i - 1)
            else:
                return findTopKth(i + 1, right)
        return findTopKth(0, len(nums) - 1)

程序2:时间复杂度还是很高

在这里插入图片描述

class Solution:
    def findKthLargest(self, nums: List[int], k: int) -> int:
        a=self.fast_sort(nums, 0, len(nums)-1, k)
        return nums[len(nums)-k]
        
    def fast_sort(self,nums,first,last,k):
        if first>=last:
            return 
        low=first
        high=last
        temp=nums[first]

        while low<high:
            #从后往前找,找到一个就交换
            while nums[high]>=temp and low<high:
                high-=1
            nums[low]=nums[high]

            #从前往后找,找到一个就交换
            while nums[low]<temp and low<high:
                low+=1
            nums[high]=nums[low]

        #将参考值放到中间,此时low=high
        nums[low]=temp

        #递归遍历标准值右边子序列
        self.fast_sort(nums, low+1, last, k)

        #递归遍历标准值左边子序列    
        self.fast_sort(nums, first, low, k)

        return nums

这道题和之前做的可能不太一样,要求复杂度低优先,之后再更新一下这道题的其他做法,欢迎大家积极评论

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

白舟的博客

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

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

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

打赏作者

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

抵扣说明:

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

余额充值