Skip to content

Commit 4a27dad

Browse files
pmjuupmjuu
authored andcommitted
feat: solve top k frequent elements
1 parent 69a28ae commit 4a27dad

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
from collections import Counter
2+
from typing import List
3+
4+
class Solution:
5+
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
6+
# ๋นˆ๋„ ๊ณ„์‚ฐ
7+
count = Counter(nums)
8+
n = len(nums)
9+
10+
# ๋นˆ๋„์ˆ˜๋ฅผ ๊ธฐ์ค€์œผ๋กœ ๋ฒ„ํ‚ท ์ƒ์„ฑ (0์—์„œ n๊นŒ์ง€)
11+
buckets = [[] for _ in range(n + 1)]
12+
13+
# ๊ฐ ์ˆซ์ž๋ฅผ ํ•ด๋‹น ๋นˆ๋„์ˆ˜์˜ ๋ฒ„ํ‚ท์— ์ถ”๊ฐ€
14+
for num, freq in count.items():
15+
buckets[freq].append(num)
16+
17+
# ๋นˆ๋„๊ฐ€ ๋†’์€ ์ˆœ์„œ๋Œ€๋กœ k๊ฐœ์˜ ์ˆซ์ž๋ฅผ ์ถ”์ถœ
18+
result = []
19+
for freq in range(n, 0, -1):
20+
if buckets[freq]:
21+
result.extend(buckets[freq])
22+
23+
if len(result) == k:
24+
return result

0 commit comments

Comments
ย (0)