Skip to content

Commit 4841b41

Browse files
committed
top-k-frequent-elements solution
1 parent e0ae448 commit 4841b41

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

top-k-frequent-elements/sun912.py

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
"""
2+
TC : O(klogn)
3+
4+
used max heap
5+
index -> count number
6+
list value -> frequent nums
7+
"""
8+
9+
class Solution:
10+
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
11+
count = {}
12+
freq = [[] for i in range(len(nums)+1)]
13+
14+
for num in nums:
15+
count[num] = 1 + count.get(num, 0)
16+
for key, val in count.items():
17+
freq[val].append(key)
18+
19+
result = []
20+
for i in range(len(freq) - 1, 0, -1):
21+
for n in freq[i]:
22+
result.append(n)
23+
if len(result) == k:
24+
return result

0 commit comments

Comments
 (0)