Skip to content

Commit 4b0908b

Browse files
committed
Solve LC > top-k-frequent-elements
1 parent 2af581d commit 4b0908b

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed

top-k-frequent-elements/bemelon.py

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
from collections import defaultdict
2+
3+
class Solution:
4+
def topKFrequent(self, nums: list[int], k: int) -> list[int]:
5+
"""
6+
Time complexity: O(nlogn)
7+
Space complexity: O(n)
8+
"""
9+
if len(nums) == k:
10+
return list(set(nums))
11+
12+
num_cnt = defaultdict(int)
13+
for num in nums:
14+
num_cnt[num] += 1
15+
16+
return list(
17+
sorted(
18+
num_cnt,
19+
key=lambda x: num_cnt[x],
20+
reverse=True
21+
)
22+
)[:k]

0 commit comments

Comments
 (0)