class MyTopK:
def topK(self,k: int, nums: list):
heap = self.buidHeap(nums[0:k])
for i in range(k,len(nums)):
if nums[i] > heap[0]:
heap[0] = nums[i]
heap[0],heap[-1] = heap[-1], heap[0]
heap = self.buidHeap(heap)
return heap
def buidHeap(self,heap:list):
# 数组中的数据是按照二叉树 层次遍历的,自下而上,遍历所有根节点, 将最小值放入根节点
heap_len = len(heap)
for i in range(heap_len // 2,-1,-1):
left, right = 2*i + 1,2*i + 2
if left < heap_len and heap[left] < heap[i]:
heap[left], heap[i] = heap[i], heap[left]
if right < heap_len and heap[right] < heap[i]:
heap[right], heap[i] = heap[i], heap[right]
return heap
pass
if __name__ == '__main__':
s = MyTopK().topK(5,[2,3,6,1,8,23,56,78,12])
print(s)