题目描述:
解决方案一:计数函数直接返回
代码如下:
class Solution(object):
def topKFrequent(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: List[int]
"""
return [item[0] for item in collections.Counter(nums).most_common(k)]
提交结果:
解决方案二:桶排序
代码如下:
class Solution(object):
def topKFrequent(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: List[int]
"""
from collections import Counter
c = Counter(nums)
buckets = [[] for _ in range(len(nums) + 1)]
for x, y in c.items():
buckets[y].append(x)
res = []
for i in range(len(nums), -1, -1):
if len(res) > k:
break
res.extend(buckets[i])
return res[:k]
提交结果: