forked from onlybooks/python-algorithm-interview
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path31-1.py
More file actions
19 lines (15 loc) · 530 Bytes
/
31-1.py
File metadata and controls
19 lines (15 loc) · 530 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import collections
import heapq
from typing import List
class Solution:
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
freqs = collections.Counter(nums)
freqs_heap = []
# 힙에 음수로 삽입
for f in freqs:
heapq.heappush(freqs_heap, (-freqs[f], f))
topk = list()
# k번 만큼 추출, 민 힙 이므로 가장 작은 음수 순으로 추출
for _ in range(k):
topk.append(heapq.heappop(freqs_heap)[1])
return topk