347. Top K Frequent Elements
solution
import collections
class Solution:
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
res = dict(collections.Counter(nums))
res = sorted(res.items(), key=lambda x: x[1], reverse=True)
return [i[0] for i in res[-k:]]import collections
import heapq
class Solution:
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
freq_dict = collections.defaultdict(int)
for num in nums:
freq_dict[num] += 1
heap = []
for num, freq in freq_dict.items(): # heap如果最小堆中按第一个元素升序顺序排
heapq.heappush(heap, (-freq, num))
res = []
for _ in range(k):
res.append(heapq.heappop(heap)[1])
return resfollow up
Last updated