classSolution:deftopKFrequent(self, nums: List[int], k:int)-> List[int]:
count = collections.defaultdict(int)for val in nums:
count[val]+=1returnsorted(count.keys(), key =lambda x : count[x], reverse =True)[:k]
2 堆 O(nlogk)
classSolution:deftopKFrequent(self, nums: List[int], k:int)-> List[int]:
heap =[]
count = collections.defaultdict(int)for num in nums:
count[num]+=1for key, val in count.items():iflen(heap)< k:# remember to change the order
heappush(heap,(val, key))elif val > heap[0][0]:
heapreplace(heap,(val, key))return[_[1]for _ in heap]