Skip to content

Commit 6f0b00b

Browse files
author
sejineer
committed
tok-k-frequent-elements solution
1 parent 3d032d8 commit 6f0b00b

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
"""
2+
시간 복잡도 O(N)
3+
공간 복잡도 O(N)
4+
5+
Priority Queue 를 이용한 풀이
6+
시간 복잡도 O(Nlog(N))
7+
공간 복잡도 O(N)
8+
from queue import PriorityQueue
9+
from collections import Counter
10+
11+
class Solution:
12+
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
13+
counter = Counter(nums)
14+
que = PriorityQueue()
15+
16+
for num, freq in counter.items():
17+
que.put((-freq, num))
18+
19+
res = []
20+
21+
for _ in range(k):
22+
res.append(que.get()[1])
23+
24+
return res
25+
"""
26+
from collections import Counter
27+
28+
class Solution:
29+
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
30+
freq_map = Counter(nums)
31+
32+
bucket = [[] for _ in range(len(nums) + 1)]
33+
34+
for num, freq in freq_map.items():
35+
bucket[freq].append(num)
36+
37+
result = []
38+
39+
for i in range(len(bucket) - 1, -1, -1):
40+
if bucket[i]:
41+
for num in bucket[i]:
42+
result.append(num)
43+
if len(result) == k:
44+
return result
45+

0 commit comments

Comments
 (0)