-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path347. Top K Frequent Elements
59 lines (42 loc) · 1.31 KB
/
347. Top K Frequent Elements
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
‘’‘
347. Top K Frequent Elements
Medium
1322
87
Favorite
Share
Given a non-empty array of integers, return the k most frequent elements.
Example 1:
Input: nums = [1,1,1,2,2,3], k = 2
Output: [1,2]
Example 2:
Input: nums = [1], k = 1
Output: [1]
Note:
You may assume k is always valid, 1 ≤ k ≤ number of unique elements.
Your algorithm's time complexity must be better than O(n log n), where n is the array's size.
’‘’
class Solution:
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
# from collections import defaultdict
# # counter
# d_key_counter = defaultdict(int)
# # key:counts
# for n in nums:
# d_key_counter[n] += 1
from collections import Counter
d_key_counter = Counter(nums)
frequency = [] # min heap
for ele, count in d_key_counter.items():
# if len(frequency) < k:
# heapq.heappush(frequency, (count, ele))
# elif frequency[0][0] < count:
# heapq.heapreplace(frequency, (count, ele))
heapq.heappush(frequency, (count, ele))
if len(frequency) > k:
heapq.heappop(frequency)
#print(frequency)
res = []
for count,ele in frequency:
res.append(ele)
return res