题目:给定一个数组,输出 前k个高频元素。
思路:
遍历数组,建立小根堆(小根堆的元素是元组(num,freq),排序规则是每个元素的频率)。
下面使用数组‘heap’,函数’shift_down’,函数‘shift_up’等实现小根堆及其调整(上浮、下沉)。
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
def shift_down(arr,root,k):# 下沉的原因是,新换了堆顶,我们需要为这个堆顶元素找到它在堆中的正确位置
# k表示目前堆的有效大小
val=arr[root] # root node : <num,freq>
while root<<1 <k