forked from alqamahjsr/Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Partho Biswas
committed
Nov 10, 2019
1 parent
1959365
commit 0557bb6
Showing
2 changed files
with
39 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |