Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Main #3

Merged
merged 4 commits into from
Apr 11, 2022
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
O(nlogk) time and O(n) space using max heap.
  • Loading branch information
149ps committed Apr 9, 2022
commit e474eec4d469eafd22838d360447bee40c86acf0
Original file line number Diff line number Diff line change
@@ -1,17 +1,9 @@
class Solution:
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
hmap = {}
for item in nums:
if hmap.get(item):
hmap[item] += 1
else:
hmap[item] = 1
result = []
heapq.heapify(result)
for key,val in hmap.items():
if len(result) < k:
heapq.heappush(result,(val,key))
else:
if val > result[0][0]:
heapq.heapreplace(result,(val,key))
return [arr[1] for arr in result]
#Calculate the frequency of all the elements in an array.
hmap = collections.Counter(nums)
# Create a max_heap of size n. (We can create a max_heap using min_heap by multiplying frequency by -1.)
max_heap = [(-v,k) for k,v in hmap.items()]
heapq.heapify(max_heap)
#pop k elements from max_heap.
return [heapq.heappop(max_heap)[1] for _ in range(k)]