Skip to content

Commit fb33970

Browse files
committed
top-k-frequent-elements solution
1 parent e4e3140 commit fb33970

File tree

1 file changed

+12
-5
lines changed

1 file changed

+12
-5
lines changed
Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,16 @@
1+
"""
2+
time complexity: O(nlogn)
3+
space complexity: O(n)
4+
"""
5+
6+
from typing import List
17
from collections import Counter
2-
import heapq
8+
from heapq import nlargest
9+
10+
class Solution:
11+
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
12+
count = Counter(nums)
13+
return [num for num, _ in nlargest(k, count.items(), key=lambda x: x[1])]
314

415

5-
class Solution(object):
6-
def topKFrequent(self, nums, k):
7-
counter = sorted(Counter(nums).items(), key=lambda item: -item[1])
8-
return list(num for num, count in counter[:k])
916

0 commit comments

Comments
 (0)