-
Notifications
You must be signed in to change notification settings - Fork 0
/
#347 topKFrequent.py
49 lines (40 loc) · 1.14 KB
/
#347 topKFrequent.py
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
class Solution:
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
# Solution 1, O(n)
count = Counter(nums)
frequency = defaultdict(list)
for c in count:
frequency[count[c]].append(c)
ans = []
for i in range(len(nums), -1, -1):
ans.extend(frequency[i])
return ans[:k]
# Solution 2, O(n log n)
# pq = []
# count = Counter(nums)
# for n in count:
# heappush(pq, (-count[n], n))
# ans = []
# for i in range(k):
# ans.append(heappop(pq)[1])
# return ans
# Solution 3, O(n)
# count = {}
# buckets = [[] for _ in range(len(nums))]
#
# for num in nums:
# count[num] = count.get(num, 0) + 1
#
# for num in count:
# buckets[count[num] - 1].append(num)
#
# j = len(nums) - 1
#
# ans = []
# while len(ans) < k:
# if len(buckets[j]) > 0:
# ans.append(buckets[j].pop())
# else:
# j -= 1
#
# return ans