赞
踩
代码如下:
- 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]
提交结果:
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。