class Solution:
# 小根堆调整
def heapAdjust(self,L,start,end):
i = start; j = 2*i; temp = L[start]
while j <= end:
if j < end and L[j][1] > L[j+1][1]:
j = j+1
if temp[1] > L[j][1]:
L[i] = L[j]; i = j; j = 2*i
else:
break
L[i] = temp
# 建立小根堆
def heapify(self,L, start, end):
firstSortCount = end // 2
for i in range(firstSortCount):
self.heapAdjust(L,firstSortCount - i, end)
return L
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
dict1 = {}
for i in nums: # 哈希表,复杂度O(n)
if i not in dict1.keys():
dict1[i]= 1
else:
dict1[i] = dict1[i] + 1
List2 = [-1] # 第一个元素占位
for item in dict1.keys():
List2.append((item,dict1[item])) # 往列表里添加元组(key,nums)
self.heapify(List2,1,k) # 列表[1:k]的元素建堆, 自底向上建堆 复杂度O(n)
for item in List2[k+1:len(List2)]: # 获取top k ,遍历剩下的元素 ,复杂度O(nlogk)
if item[1] > List2[1][1]: # 如果比堆顶元素大,就替换堆顶元素
List2[1] = item
self.heapAdjust(List2,1,k) # 替换后,调整为小根堆
res = [i[0] for i in List2[1:k+1] ]
res.sort() #对结果排序 复杂度O(klogk)
return res