Skip to content

Commit 903bc2e

Browse files
committed
added 2nd solution to top-k-frequent-elements
1 parent 7123351 commit 903bc2e

File tree

1 file changed

+15
-1
lines changed

1 file changed

+15
-1
lines changed

top-k-frequent-elements/yayyz.py

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,21 @@
1+
# Solution 1: using Counter, heapq
12
from collections import Counter
23
import heapq
34

45
class Solution:
56
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
6-
count_dict = Counter(nums)
7+
count_dict = Counter(nums)
78
return heapq.nlargest(k, count_dict.keys(), key=count_dict.get)
9+
10+
# Solution 2: create dict, use sorted function
11+
# class Solution:
12+
# def topKFrequent(self, nums: List[int], k: int) -> List[int]:
13+
# freq_dict = {}
14+
# for num in nums:
15+
# if num in freq_dict:
16+
# freq_dict[num] += 1
17+
# else:
18+
# freq_dict[num] = 1
19+
# sorted_list = sorted(freq_dict.keys(), key = lambda x: freq_dict[x], reverse=True)
20+
# return sorted_list[:k]
21+

0 commit comments

Comments
 (0)