leetcode 0215 找数组中的第k个最大元素

leetcode0215 找数组中的第k个最大元素

<一>快速选择

原理参见leedcode官方题解

时间复杂度 : 平均情况 O ( N ) O(N) O(N),最坏情况 O ( N 2 ) O(N^2) O(N2)

空间复杂度 : O ( 1 ) O(1) O(1)

执行用时 :140 ms, 在所有 Python3 提交中击败了31.22% 的用户

内存消耗 :14.1 MB, 在所有 Python3 提交中击败了52.42%的用户

class Solution:
    def findKthLargest(self, nums, k):
        def partition(left, right, pivot_index):
            pivot=nums[pivot_index]
            nums[pivot_index],nums[right]=nums[right],nums[pivot_index]
            a = left  #保证a左边的都是大于pivot的

            for i in range(left, right):
                if nums[i] > pivot:
                    nums[a],nums[i]=nums[i],nums[a]
                    a+=1

            nums[a],nums[right]=nums[right],nums[a]
            return  a

        def select(left:int, right:int, k_smallest):
            if left==right:return nums[left]
            index=random.randint(left,right)
            index= partition(left,right,index)

            if index ==k_smallest: return nums[index]
            if index < k_smallest: return select(index+1,right,k_smallest)
            if index > k_smallest : return  select(left,index-1,k_smallest)
        return select(0,len(nums)-1,k-1)


<二>用sort全排

时间复杂度: O ( N l o g 2 N ) O( N log_2 N) ONlog2N)

执行用时 :60 ms, 在所有 Python3 提交中击败了96.95% 的用户

内存消耗 :14 MB, 在所有 Python3 提交中击败了52.96%的用户

class Solution:
    def findKthLargest(self, nums: List[int], k: int) -> int:
        nums.sort()
        tt=len(nums)
        return nums[tt-k]

<三> 自定义sort排序规则

执行用时 :92 ms, 在所有 Python3 提交中击败了48.58% 的用户

内存消耗 :14 MB, 在所有 Python3 提交中击败了52.85%的用户

import functools
class Solution:
    def findKthLargest(self, nums: List[int], k: int) -> int:
      def cmp(a, b):
        if b < a: return -1
        if a < b:return 1
        return 0

      nums=sorted(nums,key=functools.cmp_to_key(cmp))
      return nums[k-1]

<四>用heapq的模块化函数

执行用时 :68 ms, 在所有 Python3 提交中击败了91.53% 的用户

内存消耗 :14.1 MB, 在所有 Python3 提交中击败了52.63%的用户

时间复杂度 : O ( N l o g 2 ⁡ k ) O(Nlog_2⁡k) O(Nlog2k)

空间复杂度 : O ( k ) O(k) O(k),用于存储堆元素。

class Solution:
    def findKthLargest(self, nums, k):
        
        return heapq.nlargest(k, nums)[-1]

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

是Mally呀!

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

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

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

打赏作者

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

抵扣说明:

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

余额充值