一、leetcode地址
https://leetcode.com/problems/kth-largest-element-in-an-array/
二、问题描述
在这里插入图片描述
三、代码实现
语言:Python3
代码:
class Solution:
def findKthLargest(self, nums: List[int], k: int) -> int:
def build_heap(parent,heap):
child = 2*parent + 1
while child < len(heap):
if child + 1 < len(heap) and heap[child + 1] <= heap[child]:
child = child + 1
if heap[parent] < heap[child]:
break
heap[parent],heap[child] = heap[child],heap[parent]
parent,child = child,2*child+1
return heap
heap = nums[:k]
for i in range(k,-1,-1):
build_heap(i,heap)
for j in range(k,len(nums)):
if nums[j] > heap[0]:
heap[0] = nums[j]
build_heap(0,heap)
return heap[0]