1
1
# Question(#347): Given a non-empty array of integers, return the k most frequent elements.
2
2
# Solution: Use a counting sort to place the most frequent items into buckets, loop through the buckets backwards,
3
3
# (since the last bucket cooresponds to the most common item), add the items in the bucket to our result and decrement
4
- # value of k by the amount of items in the bucket
4
+ # value of k by the amount of items in the bucket. An alternate solution is to use a Heap.
5
5
6
- def topKFrequent (self , nums : List [int ], k : int ) -> List [int ]:
6
+ # Using a counting sort
7
+ def topKFrequent (nums : List [int ], k : int ) -> List [int ]:
7
8
# Make an array with len(nums) + 1 positions, because the max frequency of any element
8
9
# can coorespond to the len(nums) + 1 index.
9
10
buckets = [[] for _ in range (len (nums ) + 1 )]
@@ -23,4 +24,21 @@ def topKFrequent(self, nums: List[int], k: int) -> List[int]:
23
24
result += i
24
25
k -= len (i )
25
26
27
+ return result
28
+
29
+ # Using a max heap
30
+ def topKFrequent (nums : List [int ], k : int ) -> List [int ]:
31
+ result , heap = [], []
32
+
33
+ # Add every item to the max-heap, (Note we add -b instead of b since python supports min-heaps),
34
+ # each item consists of its count and its value.
35
+ for a , b in collections .Counter (nums ).items ():
36
+ heapq .heappush (heap , (- b , a ))
37
+
38
+ # As long as we either have items in the heap and we have k left, we want to take things
39
+ # off of the max heap. Pop the top, add the value associated with it to the result and decrement k.
40
+ while k and heap :
41
+ result += [heapq .heappop (heap )[1 ]]
42
+ k -= 1
43
+
26
44
return result
0 commit comments