Skip to content

Commit 19151db

Browse files
committed
solve: top-k-frequent-elements
1 parent a3b23af commit 19151db

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

top-k-frequent-elements/raft.py

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
class Solution:
2+
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
3+
# Frequency
4+
freq = defaultdict(int)
5+
for n in nums:
6+
freq[n] += 1
7+
8+
freq_list = []
9+
for key, val in freq.items():
10+
freq_list.append((-1 * val, key))
11+
12+
heapq.heapify(freq_list)
13+
14+
res = []
15+
for _ in range(k):
16+
res.append(heapq.heappop(freq_list)[1])
17+
18+
return res
19+
20+
# T: nlogn
21+
# S: n
22+
23+
def topKFrequent2(self, nums: List[int], k: int) -> List[int]:
24+
res = []
25+
# Frequency
26+
count = defaultdict(int)
27+
for n in nums:
28+
count[n] += 1
29+
30+
# Convert to frequency
31+
frequency = [[] for _ in range(len(nums) + 1)]
32+
for key, freq in count.items():
33+
frequency[freq].append(key)
34+
35+
# top K
36+
for freq in range(len(nums), 0, -1):
37+
for n in frequency[freq]:
38+
res.append(n)
39+
40+
if len(res) == k:
41+
return res
42+
# T: n
43+
# S: n
44+

0 commit comments

Comments
 (0)