Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit e474eec

Browse files
committed
O(nlogk) time and O(n) space using max heap.
1 parent b8c7c0e commit e474eec

File tree

1 file changed

+7
-15
lines changed

1 file changed

+7
-15
lines changed
Lines changed: 7 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,9 @@
11
class Solution:
22
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
3-
hmap = {}
4-
for item in nums:
5-
if hmap.get(item):
6-
hmap[item] += 1
7-
else:
8-
hmap[item] = 1
9-
result = []
10-
heapq.heapify(result)
11-
for key,val in hmap.items():
12-
if len(result) < k:
13-
heapq.heappush(result,(val,key))
14-
else:
15-
if val > result[0][0]:
16-
heapq.heapreplace(result,(val,key))
17-
return [arr[1] for arr in result]
3+
#Calculate the frequency of all the elements in an array.
4+
hmap = collections.Counter(nums)
5+
# Create a max_heap of size n. (We can create a max_heap using min_heap by multiplying frequency by -1.)
6+
max_heap = [(-v,k) for k,v in hmap.items()]
7+
heapq.heapify(max_heap)
8+
#pop k elements from max_heap.
9+
return [heapq.heappop(max_heap)[1] for _ in range(k)]

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /