Skip to content

Commit e372a24

Browse files
committed
Top K Frequent Elements solution
1 parent 0c21985 commit e372a24

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
class Solution:
2+
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
3+
# Naive Solution
4+
# TC : O(nlogn)
5+
# SC : O(n)
6+
7+
cnt = dict()
8+
for num in nums:
9+
cnt[num] = cnt.get(num, 0) + 1
10+
11+
"""
12+
ret = dict(sorted(cnt.items(), key=lambda x:(-x[1], x[0])))
13+
return list(ret.keys())[:k]
14+
"""
15+
16+
# Follow up Solution
17+
# TC : O(nlog(k))
18+
# SC : O(n)
19+
20+
import heapq
21+
22+
ret = [(-c, num) for num, c in cnt.items()]
23+
heapq.heapify(ret)
24+
25+
return [heapq.heappop(ret)[1] for _ in range(k)]
26+

0 commit comments

Comments
 (0)