题目链接:https://leetcode.com/problems/kth-largest-element-in-an-array/submissions/
代码
class Solution:
def findKthLargest(self, nums: List[int], k: int) -> int:
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
heap=[-float('inf')]*k
heapq.heapify(heap)
for val in nums:
# print(heap)
if val > heapq.nsmallest(1,heap)[0]:
heapq.heapreplace(heap, val)
return heapq.heappop(heap)
思路详解
采用最小堆的方式