跳过正文
  1. leetcode 题解/

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

·45 字·1 分钟

类型:堆

    1. 数组中的第K个最大元素 💛

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

    ❓ 在数组中找到第 k 大的元素。

    💡 堆

    这是一个典型的堆题。

    class Solution:
        def findKthLargest(self, nums: List[int], k: int) -> int:
            h = []
            for num in nums:
                if len(h) < k or num > h[0]:
                    heapq.heappush(h, num)
                if len(h) > k:
                    heapq.heappop(h)
            return h[0]