We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent 69a28ae commit 4a27dadCopy full SHA for 4a27dad
โtop-k-frequent-elements/pmjuu.pyโ
@@ -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