-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtop_k_frequent_elements.py
More file actions
29 lines (22 loc) · 977 Bytes
/
top_k_frequent_elements.py
File metadata and controls
29 lines (22 loc) · 977 Bytes
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
from typing import List
class Solution:
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
bucketSortedByFrequencyArray = [
[] for _ in range(len(nums) + 1)
] # frequency is the index of the array
frequencyHashmap = {} # value : frequency
outputArray = []
for num in nums:
if num in frequencyHashmap:
frequencyHashmap[num] = frequencyHashmap[num] + 1
else:
frequencyHashmap[num] = 1
for element in frequencyHashmap:
bucketSortedByFrequencyArray[frequencyHashmap[element]].append(element)
for frequency in range(len(bucketSortedByFrequencyArray) - 1, 0, -1):
for val in bucketSortedByFrequencyArray[frequency]:
outputArray.append(val)
if len(outputArray) == k:
return outputArray
solution = Solution()
print(solution.topKFrequent([1, 1, 1, 2, 2, 3], 2))