[LeetCode] 215. Kth Largest Element in an Array @ python

一.题目:
给定一个数组,找到其中第k大的元素
二.解题思路:
(1)直接使用heapq库中的函数,代码很简单:

class Solution(object):
    def findKthLargest(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: int
        """
        #heapq方法
        return heapq.nlargest(k,nums)[-1]

(2)使用python自带的排序函数,代码也很简单:

class Solution(object):
    def findKthLargest(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: int
        """
        #sorted方法
       return sorted(nums,reverse=True)[k-1]

(3)使用快速排序算法,代码如下:

class Solution(object):
    def findKthLargest(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: int
        """
        #sorted方法
       # return sorted(nums,reverse=True)[k-1]
        #heapq方法
        # return heapq.nlargest(k,nums)[-1]
        #快速排序方法
        def dfs(nums,k):
            #一个数的时候,直接返回
            if len(nums) == 1: return nums[0]
            #取参照数
            x = nums[0]
            #定义左右区间
            i = 1; j = len(nums)-1
            #循环执行交换过程
            while ( i < j ):
                while ( i < j and nums[i] >= x ): i += 1
                while ( i < j and nums[j] <= x ): j -= 1
                if i == j: break
                nums[i],nums[j] = nums[j],nums[i]
                
            #退出的时候,判断nums[i]和x的关系,来决定如何交换
            if nums[i] >= x:
                nums[0],nums[i] = nums[i],nums[0]
            else:
                nums[0],nums[i-1] = nums[i-1],nums[0]
                i -= 1
            #根据i的位置来决定递归方向
            if i == k-1: return nums[i]
            elif k > i:
                return dfs(nums[i+1:],k-i-1)
            else:
                return dfs(nums[:i],k)
            
        return dfs(nums,k)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值