nums
k
-freq
를 우선순위로 넣어주기(클수록 우선순위 빠르도록) from collections import defaultdict
from heapq import heappush, heappop
class Solution:
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
# counting frequency
freq = defaultdict(int)
for num in nums:
freq[num] += 1
# sort by frequency
sortedList = []
for key in freq:
heappush(sortedList, [-freq[key], key]) # [priority, num]
# finding k freq num.
ans = []
while k > 0 and sortedList:
ans.append(heappop(sortedList)[1])
k -= 1
return ans
from collections import defaultdict
class Solution:
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
# counting frequency
freq = defaultdict(int)
for num in nums:
freq[num] += 1
# sort by frequency
li = [[num, freq[num]] for num in freq]
li.sort(key=lambda x: x[1], reverse=True)
ans = [el[0] for el in li]
return ans[:k]
그냥 정렬을 이용한 두번째 풀이가 조금 더 빠르다...