classSolution:deffindKthLargest(self,nums: List[int],k:int) ->int: heap = nums[:k]# 建堆for i inrange(k //2-1, -1, -1): self.adjust_heap(heap, i, k)# 调整堆for i inrange(k, len(nums)):if nums[i]> heap[0]: heap[0]= nums[i] self.adjust_heap(heap, 0, k)return heap[0]defadjust_heap(self,array,i,size): child = i *2+1while child < size:if child +1< size and array[child +1]< array[child]: child +=1if array[child]> array[i]:break array[i], array[child]= array[child], array[i] i = child child = i *2+1
import heapqclassSolution:deffindKthLargest(self,nums: List[int],k:int) ->int: heap = []for num in nums[:k]: heapq.heappush(heap, num)for num in nums[k:]:if num > heap[0]: heapq.heapreplace(heap, num)return heap[0]