|
1 | | -# Time: O(n) ~ O(n^2), O(n) on average. |
| 1 | +# Time: O(n) |
2 | 2 | # Space: O(n) |
3 | 3 |
|
4 | 4 | # Given a non-empty array of integers, |
|
13 | 13 | # Your algorithm's time complexity must be better |
14 | 14 | # than O(n log n), where n is the array's size. |
15 | 15 |
|
16 | | -from random import randint |
17 | | - |
| 16 | +# Bucket Sort Solution |
18 | 17 | class Solution(object): |
| 18 | + def topKFrequent(self, nums, k): |
| 19 | + """ |
| 20 | + :type nums: List[int] |
| 21 | + :type k: int |
| 22 | + :rtype: List[int] |
| 23 | + """ |
| 24 | + counts = collections.defaultdict(int) |
| 25 | + for i in nums: |
| 26 | + counts[i] += 1 |
| 27 | + buckets = [[] for _ in xrange(len(nums)+1)] |
| 28 | + for i, count in counts.iteritems(): |
| 29 | + buckets[count].append(i) |
| 30 | + |
| 31 | + result = [] |
| 32 | + for i in reversed(xrange(len(buckets))): |
| 33 | + for j in xrange(len(buckets[i])): |
| 34 | + result.append(buckets[i][j]) |
| 35 | + if len(result) == k: |
| 36 | + return result |
| 37 | + return result |
| 38 | + |
| 39 | + |
| 40 | +# Time: O(n) ~ O(n^2), O(n) on average. |
| 41 | +# Space: O(n) |
| 42 | +# Quick Select Solution |
| 43 | +from random import randint |
| 44 | +class Solution2(object): |
19 | 45 | def topKFrequent(self, nums, k): |
20 | 46 | """ |
21 | 47 | :type nums: List[int] |
@@ -64,7 +90,7 @@ def PartitionAroundPivot(left, right, pivot_idx, nums): |
64 | 90 |
|
65 | 91 | # Time: O(nlogk) |
66 | 92 | # Space: O(n) |
67 | | -class Solution2(object): |
| 93 | +class Solution3(object): |
68 | 94 | def topKFrequent(self, nums, k): |
69 | 95 | """ |
70 | 96 | :type nums: List[int] |
|
0 commit comments