时间复杂度(O(nlogk)), 思想:dict_count+堆排序
class Solution:
def update_top_k(self, top_k: [[int, int]], num_count: (int, int)):
if top_k[0][1] >= num_count[1]: return
top_k[0] = num_count
parent_index, child_index = 0, 1
top_k_len = len(top_k)
while child_index < top_k_len:
if child_index + 1 < top_k_len and top_k[child_index][1] > top_k[child_index + 1][1]:
child_index += 1
if top_k[child_index][1] >= top_k[parent_index][1]:
break
top_k[child_index], top_k[parent_index] = top_k[parent_index], top_k[child_index]
parent_index, child_index = child_index, child_index * 2 + 1
def topKFrequent(self, nums: [int], k: int) -> [int]:
num_dict = {}
for num in nums:
if num not in num_dict:
num_dict[num] = 1
else:
num_dict[num] += 1
r_count = [[-1, -1] for _ in range(k)]
for num in num_dict:
self.update_top_k(r_count, (num, num_dict[num]))
return [num[0] for num in r_count]