leetcode-215 第k大元素

leetcode-215 第k大元素

(leetcode 215) 在未排序的数组中找到第 k 个最大的元素。请注意,你需要找的是数组排序后的第 k 个最大的元素,而不是第 k 个不同的元素。

解法一:简单粗暴,取出k-1个最大数;时间复杂度为(nk)

class Solution:
    def findKthLargest(self, nums: List[int], k: int) -> int:
        for i in range(k-1):
            nums.remove(max(nums))
        return max(nums)

解法二:大顶堆;复杂度小

from heapq import *

class Solution:
    def findKthLargest(self, nums: List[int], k: int) -> int:
        if not nums:
            return False
        h = []
        for i in range(len(nums)):
            if len(h) < k:
                heappush(h,nums[i])
            else:
                if h[0] < nums[i]:
                    heappop(h)
                    heappush(h,nums[i])
        return h[0]
原文地址:https://www.cnblogs.com/curtisxiao/p/11207653.html