-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtopKFrequentElements.py
More file actions
35 lines (28 loc) · 1005 Bytes
/
Copy pathtopKFrequentElements.py
File metadata and controls
35 lines (28 loc) · 1005 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
30
31
32
33
34
35
# import heapq
class Solution:
# time: O(n logk), space: O(n)
# def topKFrequent(self, nums: list[int], k: int) -> list[int]:
# frequency = {}
# for n in nums:
# frequency[n] = frequency.get(n, 0) + 1
# heap = []
# for key, freq in frequency.items():
# heapq.heappush(heap, (freq, key))
# if len(heap) > k:
# heapq.heappop(heap)
# return [n for _, n in heap]
# time: O(n), space: O(n)
def topKFrequent(self, nums: list[int], k: int) -> list[int]:
buckets = [[] for _ in range(len(nums)+1)]
freq = {}
for n in nums:
freq[n] = freq.get(n, 0) + 1
for key, value in freq.items():
buckets[value].append(key)
res = []
for i in range(len(buckets) - 1, -1, -1):
for j in buckets[i]:
res.append(j)
if len(res) == k:
return res
return res