File tree Expand file tree Collapse file tree 1 file changed +28
-0
lines changed Expand file tree Collapse file tree 1 file changed +28
-0
lines changed Original file line number Diff line number Diff line change
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 ]
You can’t perform that action at this time.
0 commit comments