[Course] Advanced Computer Programming, Homework, week 9-2, LeetCode 215. Kth Largest Element

本文介绍了一种利用快速选择算法解决寻找序列中第K大元素的问题的方法。通过随机选择并划分数组,逐步缩小查找范围,最终找到目标元素。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

215. Kth Largest Element in an Array

题目来源

https://leetcode.com/problems/kth-largest-element-in-an-array/description/

题意分析

找出序列中第k大元素

题目思路

用快速选择算法求解,即随机选择数组中的一个数,进行划分,若划分的这个数恰好是第k大,那么返回结果。若不是,则对对应的子数组进行递归求解。

伪代码如下:

代码

import random

class Solution:
    def findKthLargest(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: int
        """
        return Solution().quick_select(nums, 0, len(nums), k-1)

    def quick_select(self, a, x, y, k):
        if y-x<=1:
            return a[x]

        rd = random.randint(x, y-1)
        a[rd],a[y-1] = a[y-1],a[rd]

        v = a[y-1]
        j = x
        for i in range(x,y-1):
            if a[i]>v:
                a[i],a[j] = a[j],a[i]
                j+=1

        a[j],a[y-1] = a[y-1],a[j]
        if k==j:
            return a[j]
        elif k<j:
            return Solution().quick_select(a,x,j,k)
        else:
            return Solution().quick_select(a,j+1,y,k)

结果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值