-
-
Notifications
You must be signed in to change notification settings - Fork 298
/
Copy path347.py
23 lines (21 loc) · 935 Bytes
/
347.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
__________________________________________________________________________________________________
sample 96 ms submission
class Solution:
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
ans= collections.Counter(nums).most_common(k)
return [a[0] for a in ans]
__________________________________________________________________________________________________
sample 15640 kb submission
from collections import Counter
import heapq
class Solution:
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
counter = Counter(nums)
heap = []
for num, count in counter.items():
if len(heap) == k:
heapq.heappushpop(heap, (count, num))
else:
heapq.heappush(heap, (count, num))
return [num for _, num in heap]
__________________________________________________________________________________________________