Skip to main content

347. Top K Frequent Elements

https://leetcode.com/problems/top-k-frequent-elements/

Python

Count and sort

from collections import Counter


class Solution:
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
counts = [(num, count) for num, count in Counter(nums).items()]
counts.sort(key=lambda item: item[1], reverse=True)

return [count[0] for count in counts[:k]]

Heap

import heapq
from collections import Counter


class Solution:
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
counts = Counter(nums)

return heapq.nlargest(k, counts.keys(), key=counts.get)