调库大根堆
class Solution:
def findKthLargest(self, nums: List[int], k: int) -> int:
maxHeap = []
for x in nums:
heapq.heappush(maxHeap, -x)
for _ in range(k - 1):
heapq.heappop(maxHeap)
return -maxHeap[0]
手写大根堆
class Solution:
def findKthLargest(self, nums: List[int], k: int) -> int:
n = len(nums)
self.build_maxHeap(nums)
for i in range(k-1):
nums[0], nums[n-1-i] = nums[n-1-i], nums[0]
self.adjust_down(nums, 0, n-1-i-1)
return nums[0]
def build_maxHeap(self, nums: List[int]) -> None:
n = len(nums)
for root in range(n//2, -1, -1):
self.adjust_down(nums, root, n - 1)
def adjust_down(self, nums: List[int], root: int, hi: int) -> None:
if root > hi:
return
t = nums[root]
child = 2 * root + 1
while child <= hi:
if child + 1 <= hi and nums[child] < nums[child + 1]:
child += 1
if t >= nums[child]:
break
nums[root] = nums[child]
root = child
child = 2 * root + 1
nums[root] = t