Skip to content

Commit ad49bf0

Browse files
authored
Update Top K Frequent Elements - Leetcode 347.py
1 parent c6e59f9 commit ad49bf0

File tree

1 file changed

+17
-0
lines changed

1 file changed

+17
-0
lines changed

Top K Frequent Elements - Leetcode 347/Top K Frequent Elements - Leetcode 347.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,20 @@
1+
# Heap Solution:
2+
from collections import Counter
3+
import heapq
4+
class Solution:
5+
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
6+
counter = Counter(nums)
7+
heap = []
8+
9+
for key, val in counter.items():
10+
if len(heap) < k:
11+
heapq.heappush(heap, (val, key))
12+
else:
13+
heapq.heappushpop(heap, (val, key))
14+
15+
return [h[1] for h in heap]
16+
# Time: O(n log k), Space: O(k)
17+
118
from collections import Counter
219
class Solution:
320
def topKFrequent(self, nums: List[int], k: int) -> List[int]:

0 commit comments

Comments
 (0)