Leetcode 215. Kth Largest Element in an Array

该文章介绍了一种基于快速排序思想的算法,用于在给定的整数数组中找到第k个最大的元素。算法首先随机选择一个枢轴,然后重新排列数组,使得小于枢轴的元素都在其左侧,大于等于枢轴的在右侧。根据k与枢轴位置的关系,递归地在左侧或右侧子数组中查找目标元素,确保在整个过程中保持O(n)的时间复杂度。
摘要由CSDN通过智能技术生成

Problem

Given an integer array nums and an integer k, return the kth largest element in the array.

Note that it is the kth largest element in the sorted order, not the kth distinct element.

You must solve it in O(n) time complexity.

Algorithm

Based on the quicksort algorithm.

Code

class Solution:
    def findKthLargest(self, nums: List[int], k: int) -> int:

        def KthLargest(nums, k):
            nlen = len(nums)
            pivot = random.randint(0, nlen-1)
            if pivot:
                nums[pivot], nums[0] = nums[0], nums[pivot]
            M = 0
            for i in range(1, nlen):
                if nums[i] >= nums[0]:
                    M += 1
                    nums[M], nums[i] = nums[i], nums[M]
            nums[M], nums[0] = nums[0], nums[M]
            if k == M:
                return nums[M]
            elif k < M:
                return KthLargest(nums[0:M], k)
            else:
                return KthLargest(nums[M:], k - M)

        return KthLargest(nums, k-1)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值