- See Code
Complexity T : O( n + nlogk )
# O(n) + O(nlogk)
class Solution:
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
cnt = collections.Counter(nums)
q = []
for i, v in cnt.items():
heapq.heappush(q, (v, i))
if len(q) > k:
heapq.heappop(q)
return [n for _, n in q]