347. Top K Frequent Elements (Medium) - TengnanYao/daily_leetcode GitHub Wiki
class Solution:
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
# heap
h = collections.Counter(nums)
q = []
for key, v in h.items():
heapq.heappush(q, (-v, key))
result = []
for _ in range(k):
result.append(heapq.heappop(q)[1])
return result
# bucket sort
h = collections.Counter(nums)
m = max(h.values())
buckets = [[] for _ in range(m + 1)]
for key, v in h.items():
buckets[v].append(key)
result = []
for i in range(m, -1, -1):
result += buckets[i]
if len(result) >= k:
return result[ : k]