|
7 | 7 | # - Heap (Priority Queue) - Bucket Sort - Counting - Quickselect
|
8 | 8 |
|
9 | 9 | import timeit
|
10 |
| -from collections import Counter |
| 10 | +from collections import Counter, defaultdict |
11 | 11 | from typing import List
|
12 | 12 |
|
13 | 13 |
|
|
19 | 19 | #
|
20 | 20 | # Runtime 95 ms Beats 95.19%
|
21 | 21 | # Memory Usage 18.4 Beats 99.66%
|
22 |
| -class Solution: |
| 22 | +class UseCounter: |
23 | 23 | def topKFrequent(self, nums: List[int], k: int) -> List[int]:
|
24 | 24 | return [x[0] for x in Counter(nums).most_common(k)]
|
25 | 25 |
|
26 | 26 |
|
| 27 | +# Use bucket sorting, first get the frequency of items in the input, |
| 28 | +# then create an array of buckets and place each unique value in the |
| 29 | +# array indexed by its frequency. To create the result, iterate in |
| 30 | +# reverse over the array indexes and pop elements until the result has |
| 31 | +# grown to have k elements. |
| 32 | +# |
| 33 | +# Time complexity: O(n) - Sorting the dictionary by value. |
| 34 | +# Space complexity: O(n) - The size of the dictionary. |
| 35 | +# |
| 36 | +# Runtime 104 ms Beats 71.15% |
| 37 | +# Memory Usage 18.7 Beats 42.44% |
| 38 | +class BucketSort: |
| 39 | + def topKFrequent(self, nums: List[int], k: int) -> List[int]: |
| 40 | + # Count the frequency of each element, same as Counter(nums). |
| 41 | + freq = defaultdict(int) |
| 42 | + for num in nums: |
| 43 | + freq[num] += 1 |
| 44 | + # A bucket that holds elements indexed by their frequency. |
| 45 | + bucket = [] |
| 46 | + for num, count in freq.items(): |
| 47 | + # Expand bucket if needed. |
| 48 | + while count + 1 > len(bucket): |
| 49 | + bucket.append(None) |
| 50 | + # If empty add a list at the index. |
| 51 | + if not bucket[count]: |
| 52 | + bucket[count] = [] |
| 53 | + # Append the value indexed by its frequency. |
| 54 | + bucket[count].append(num) |
| 55 | + # Create a result of size k. |
| 56 | + res, idx = [], len(bucket) - 1 |
| 57 | + while len(res) < k: |
| 58 | + if bucket[idx]: |
| 59 | + res.append(bucket[idx].pop()) |
| 60 | + else: |
| 61 | + idx -= 1 |
| 62 | + return res |
| 63 | + |
| 64 | + |
27 | 65 | def test():
|
28 |
| - executors = [Solution] |
| 66 | + executors = [ |
| 67 | + UseCounter, |
| 68 | + BucketSort, |
| 69 | + ] |
29 | 70 | tests = [
|
30 | 71 | [[1], 1, [1]],
|
31 | 72 | [[3, 0, 1, 0], 1, [0]],
|
|
0 commit comments