Skip to content

Commit 0557bb6

Browse files
author
Partho Biswas
committed
347. Top K Frequent Elements
1 parent 1959365 commit 0557bb6

File tree

2 files changed

+39
-1
lines changed

2 files changed

+39
-1
lines changed

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -222,7 +222,8 @@ I have solved quite a number of problems from several topics. See the below tabl
222222
### [Heaps](https://www.youtube.com/watch?v=HqPJF2L5h9U)
223223
| # | Title | Solution | Tutorial | Level | Remarks |
224224
| --- | --- | --- | --- | --- | --- |
225-
|01| [253_Meeting_Rooms_II](https://leetcode.com/problems/meeting-rooms-ii//)| [Python](leetcode.com/python/253_Meeting_Rooms_II.py)| [Official](https://leetcode.com/problems/meeting-rooms-ii/solution/) | Medium | --- |
225+
|01| [253_Meeting_Rooms_II](https://leetcode.com/problems/meeting-rooms-ii/)| [Python](leetcode.com/python/253_Meeting_Rooms_II.py)| [Official](https://leetcode.com/problems/meeting-rooms-ii/solution/) | Medium | --- |
226+
|02| [347. Top K Frequent Elements](https://leetcode.com/problems/top-k-frequent-elements/solution/)| [Python](leetcode.com/python/347_Top_K_Frequent_Elements.py)| [Official](https://leetcode.com/problems/meeting-rooms-ii/solution/) | Medium | --- |
226227

227228

228229
### [Tries](https://leetcode.com/explore/learn/card/trie/)
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
from collections import Counter
2+
import heapq
3+
4+
class Solution(object):
5+
6+
# # Using only HashMap/Dictionary
7+
# def topKFrequent(self, nums, k):
8+
# """
9+
# :type nums: List[int]
10+
# :type k: int
11+
# :rtype: List[int]
12+
# """
13+
# count = Counter(nums)
14+
# elements = count.most_common(k)
15+
# common_keys = [x[0] for x in elements]
16+
# return common_keys
17+
18+
19+
# Using heap and map
20+
def topKFrequent(self, nums, k):
21+
"""
22+
:type nums: List[int]
23+
:type k: int
24+
:rtype: List[int]
25+
"""
26+
count = Counter(nums)
27+
keys = count.keys()
28+
common_keys = heapq.nlargest(k, keys, key=count.get) # key=count.get is used to sory y value in asending order
29+
return common_keys
30+
31+
32+
33+
sol = Solution()
34+
nums = [4,1,-1,2,-1,2,3]
35+
k = 2
36+
out = sol.topKFrequent(nums, k)
37+
print('Res: ',out)

0 commit comments

Comments
 (0)