LeetCode 215. 数组中的第K个最大元素

2022-09-02  本文已影响0人  草莓桃子酪酪
题目

给定整数数组 nums 和整数 k,请返回数组中第 k 个最大的元素。请注意,你需要找的是数组排序后的第 k 个最大的元素,而不是第 k 个不同的元素。
你必须设计并实现时间复杂度为 O(n) 的算法解决此问题。

例:
输入: [3,2,1,5,6,4], k = 2
输出: 5

方法一:大顶堆、API
class Solution(object):
    def findKthLargest(self, nums, k):
        maxheap = []
        for num in nums:
            heapq.heappush(maxheap, -num)
        for num in range(k-1):
            heapq.heappop(maxheap)
        return -maxheap[0]
方法二:快速排序

findKthLargest 函数:寻找数组中的第 K 个元素

partition 函数:确定基准元素处于序列中的位置,最终生成降序序列

class Solution(object):
    def findKthLargest(self, nums, k):
        left, right = 0, len(nums)-1
        while True:
            index = self.partition(nums, left, right)
            if index == k-1:
                return nums[index]
            elif index < k-1:
                left = index + 1
            else:
                right = index - 1 
    
    def partition(self, nums, left, right):
        pivot = nums[left]
        index = left
        for i in range(left+1, right+1):
            if nums[i] >= pivot:
                index += 1
                nums[index], nums[i] = nums[i], nums[index]
        nums[index], nums[left] = nums[left], nums[index]
        return index

例:[3,2,1,5,6,4], k = 2
left = 0,right = 5
index = partition(nums, 0, 5):
pivot = 3,index = 0
i = 1:nums[1] = 2 < pivot = 3
i = 2:nums[2] = 1 < pivot = 3
i = 3:nums[3] = 5 ≥ pivot = 3 index = 1 nums = [3, 5, 1, 2, 6, 4]
i = 4:nums[4] = 5 ≥ pivot = 3 index = 2 nums = [3, 5, 6, 2, 1, 4]
i = 5:nums[5] = 4 ≥ pivot = 3 index = 3 nums = [3, 5, 6, 4, 1, 2]
nums = [4, 5, 6, 3, 1, 2]
index = partition(nums, 0, 5) = 3
......

相关知识
参考

代码相关:https://leetcode.cn/problems/kth-largest-element-in-an-array/solution/cpython3java-1da-gen-dui-diao-ku-2shou-l-xveq/
堆:https://blog.csdn.net/sinat_34715587/article/details/89195447 https://blog.csdn.net/qq_38022469/article/details/123851001
快速排序:https://blog.csdn.net/qq_52595134/article/details/118943109

上一篇下一篇

猜你喜欢

热点阅读