Given a non-empty array of integers, return the k most frequent elements.
For example,
Given [1,1,1,2,2,3]
and k = 2, return [1,2]
.
Note:
- You may assume k is always valid, 1 ≤ k ≤ number of unique elements.
- Your algorithm's time complexity must be better than O(n log n), where n is the array's size.
思路:bucket sort
class Solution:
def topKFrequent(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: List[int]
"""
bucket = [[] for _ in range(len(nums)+1)]
d = {}
for i in nums: d[i] = d.get(i, 0)+1
for key in d: bucket[d[key]].append(key)
ret, i = [], len(bucket)-1
while len(ret)<k:
ret += bucket[i]
i -= 1
return ret[:k]
s=Solution()
print(s.topKFrequent([4,1,-1,2,-1,2,3], 2))