classSolution: defheapify(self, arr, i):# 大顶堆化 left, right = 2 * i + 1, 2 * i + 2 largest = i if left < len(arr) and arr[left] > arr[largest]: largest = left if right < len(arr) and arr[right] > arr[largest]: largest = right if largest != i: arr[largest], arr[i] = arr[i], arr[largest] self.heapify(arr, largest) # 交换后再次与左右子节点比较
defbuild_heap(self, nums):# 从非叶子节点初始化堆 for i in range(len(nums) // 2 - 1, -1, -1): self.heapify(nums, i)
defgetLeastNumbers(self, arr: List[int], k: int) -> List[int]: ifnot arr or k <= 0: return [] if len(arr) <= k: return arr heap = arr[:k] self.build_heap(heap) for i in range(k, len(arr)): if arr[i] < heap[0]: # 当前元素比k堆顶小时,弹出堆顶并插入当前元素 heap[0] = arr[i] self.heapify(heap, 0) return heap