python
class Solution:
def findKthLargest(self, nums: List[int], k: int) -> int:
import heapq
size = len(nums)
queue = [-nums[i] for i in range(size)] # 使用大顶堆,把所有元素取反 代表优先级
heapq.heapify(queue)
for _ in range(k - 1):
heapq.heappop(queue)
return -queue[0]
优化之后的:
- 遍历数组元素,对于当前元素
num:- 如果优先级队列中的元素个数小于
k个,则将当前元素num放入优先级队列中。 - 如果优先级队列中的元素个数大于等于
k个,并且当前元素num大于优先级队列的队头元素,则弹出队头元素,并将当前元素num插入到优先级队列中。
- 如果优先级队列中的元素个数小于
- 遍历完,此时优先级队列的队头元素就是第
k个最大元素,将其弹出并返回即可。
这里我们借助了 Python 中的 heapq 模块实现优先级队列算法,这一步也可以通过手写堆的方式实现优先级队列。
python
import heapq
class Solution:
def findKthLargest(self, nums: List[int], k: int) -> int:
res = []
for num in nums:
if len(res) < k:
heapq.heappush(res, num)
elif num > res[0]:
heapq.heappop(res)
heapq.heappush(res, num)
return heapq.heappop(res)