采用堆 O(Nlogk), 满足要求
若采用bfprt然后在排序k个字典 就是max(O(N), O(klogk)) 就会快一点
import heapq
class Solution:
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
count = {}
for i in nums:
count.setdefault(i, 0)
count[i] += 1
return [k for k, _ in heapq.nlargest(k, count.items(), key=lambda x: x[1])]