Computer Science/Coding Test
LeetCode: 347. Top K Frequent Elements
focalpoint
2021. 11. 15. 19:55
빈도를 기억하기 위한 hashmap을 사용하자.
from collections import defaultdict
class Solution:
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
dic = defaultdict(int)
for num in nums:
dic[num] += 1
temp = []
for key, val in dic.items():
temp.append([val, key])
temp.sort(key=lambda x: -x[0])
temp = temp[:k]
return [t[1] for t in temp]