日野弥生:勉強しよう

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

发表于2025年03月21日

#数组 #分治 #快速选择 #排序 #优先队列 #堆

利用优先队列进行处理即可。

class Solution:
    def findKthLargest(self, nums: List[int], k: int) -> int:
        heap = []
        def add(num: int):
            nonlocal heap
            heapq.heappush(heap, num)
            if len(heap) > k:
                heapq.heappop(heap)

        for num in nums:
            add(num)
        return heap[0]

フラッシュタブ:LeetCode

题目链接:https://leetcode.cn/problems/kth-largest-element-in-an-array/

上一篇

LeetCode 703 - 数据流中的第 K 大元素

下一篇

LeetCode 236 - 二叉树的最近公共祖先