Skip to content

Commit

Permalink
347. Top K Frequent Elements
Browse files Browse the repository at this point in the history
  • Loading branch information
Partho Biswas committed Nov 10, 2019
1 parent 1959365 commit 0557bb6
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 1 deletion.
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -222,7 +222,8 @@ I have solved quite a number of problems from several topics. See the below tabl
### [Heaps](https://www.youtube.com/watch?v=HqPJF2L5h9U)
| # | Title | Solution | Tutorial | Level | Remarks |
| --- | --- | --- | --- | --- | --- |
|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 | --- |
|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 | --- |
|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 | --- |


### [Tries](https://leetcode.com/explore/learn/card/trie/)
Expand Down
37 changes: 37 additions & 0 deletions leetcode.com/python/347_Top_K_Frequent_Elements.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
from collections import Counter
import heapq

class Solution(object):

# # Using only HashMap/Dictionary
# def topKFrequent(self, nums, k):
# """
# :type nums: List[int]
# :type k: int
# :rtype: List[int]
# """
# count = Counter(nums)
# elements = count.most_common(k)
# common_keys = [x[0] for x in elements]
# return common_keys


# Using heap and map
def topKFrequent(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: List[int]
"""
count = Counter(nums)
keys = count.keys()
common_keys = heapq.nlargest(k, keys, key=count.get) # key=count.get is used to sory y value in asending order
return common_keys



sol = Solution()
nums = [4,1,-1,2,-1,2,3]
k = 2
out = sol.topKFrequent(nums, k)
print('Res: ',out)

0 comments on commit 0557bb6

Please sign in to comment.