日野弥生:勉強しよう
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]