Skip to content

Commit f4c430d

Browse files
committed
update Python/Top_K_Frequent_Elements.py
1 parent d742b38 commit f4c430d

File tree

1 file changed

+20
-2
lines changed

1 file changed

+20
-2
lines changed

Python/Top_K_Frequent_Elements.py

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,10 @@
11
# Question(#347): Given a non-empty array of integers, return the k most frequent elements.
22
# Solution: Use a counting sort to place the most frequent items into buckets, loop through the buckets backwards,
33
# (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.
55

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]:
78
# Make an array with len(nums) + 1 positions, because the max frequency of any element
89
# can coorespond to the len(nums) + 1 index.
910
buckets = [[] for _ in range(len(nums) + 1)]
@@ -23,4 +24,21 @@ def topKFrequent(self, nums: List[int], k: int) -> List[int]:
2324
result += i
2425
k -= len(i)
2526

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+
2644
return result

0 commit comments

Comments
 (0)