-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path347 Top K Frequent Elements.py
34 lines (25 loc) · 1.22 KB
/
347 Top K Frequent Elements.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# Given an integer array nums and an integer k,
# return the k most frequent elements. You may
# return the answer in any order.
nums = [1]
k = 1
class Solution:
def topKFrequent(self, nums: list[int], k: int) -> list[int]:
# Step 1: Create a dictionary (`mp`) to store the frequency of each element in the array.
mp = {}
# Step 2: Create buckets to store elements based on their frequency.
buckets = [[] for i in range(len(nums) + 1)]
# Step 3: Iterate through the array to populate the `mp` dictionary.
for n in nums:
mp[n] = 1 + mp.get(n, 0)
# Step 4: Iterate through the items in `mp` and distribute elements into the corresponding buckets based on their frequency.
for n, c in mp.items():
buckets[c].append(n)
# Step 5: Iterate through the buckets from right to left (highest to lowest frequency) and append elements to the answer list until the desired k elements are collected.
ans = []
for i in range(len(buckets) - 1, 0, -1):
for n in buckets[i]:
ans.append(n)
if len(ans) == k:
return ans
print(Solution().topKFrequent(nums, k))