Skip to content

Commit 094b927

Browse files
committed
solve: top k frequent elements
1 parent 61a3e18 commit 094b927

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
from collections import Counter
2+
3+
4+
def top_k_frequent(nums, k):
5+
# Count the frequency of each number in the input list
6+
counter = Counter(nums)
7+
8+
# Find the maximum frequency among all numbers
9+
max_freq = max(counter.values())
10+
11+
# Create a list of empty lists (buckets) where index represents frequency
12+
buckets = [[] for _ in range(max_freq + 1)]
13+
14+
# Place each number into the bucket corresponding to its frequency
15+
for num, freq in counter.items():
16+
buckets[freq].append(num)
17+
18+
# Initialize an empty list to store the result
19+
result = []
20+
21+
# Iterate over the buckets in reverse order (from highest frequency to lowest)
22+
for freq in range(max_freq, 0, -1):
23+
# Add all numbers in the current bucket to the result
24+
result.extend(buckets[freq])
25+
26+
# If we have collected at least k elements, return the first k elements
27+
if len(result) >= k:
28+
return result[:k]

0 commit comments

Comments
 (0)