Skip to content

Commit 085e297

Browse files
author
MJ Kang
committed
try using heap solution
1 parent a309b1e commit 085e297

File tree

1 file changed

+25
-1
lines changed

1 file changed

+25
-1
lines changed

top-k-frequent-elements/mandoolala.py

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,29 @@
22

33
class Solution:
44
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
5+
'''
6+
Using (min)heap
7+
[Complexity]
8+
Time: O(log n)
9+
Space: O(n+k)
10+
'''
11+
from heapq import heappush, heappop
12+
counter = {}
13+
for num in nums:
14+
counter[num] = counter.get(num, 0) + 1
15+
heap = []
16+
for num, freq in counter.items():
17+
heappush(heap, (freq, num))
18+
if len(heap) > k:
19+
heappop(heap)
20+
return [num for _, num in heap]
21+
'''
22+
Using hash table
23+
[Complexity]
24+
Time: O(n log n)
25+
Space: O(n)
26+
'''
27+
'''
528
countDict = {}
629
for num in nums:
730
if num in countDict:
@@ -12,4 +35,5 @@ def topKFrequent(self, nums: List[int], k: int) -> List[int]:
1235
freqElements = []
1336
for i in range(k):
1437
freqElements.append(sortedDictList[i][0])
15-
return freqElements
38+
return freqElements
39+
'''

0 commit comments

Comments
 (0)