給出一個(gè)數(shù)組,輸出出現(xiàn)頻次最高的k個(gè)數(shù)(輸出的順序無(wú)限制),dict統(tǒng)計(jì)頻次再sort
1 #347
2 #Runtime: 76 ms (Beats 90.9%)
3 #Memory: 16.8 MB (Beats 53.94%)
4
5 class Solution(object):
6 def topKFrequent(self, nums, k):
7 """
8 :type nums: List[int]
9 :type k: int
10 :rtype: List[int]
11 """
12 cnt = defaultdict(lambda:0)
13 for i in nums:
14 cnt[i] += 1
15 a = sorted(cnt.items(), key=lambda item: item[1], reverse=True)
16 ans = []
17 for x in a:
18 ans.append(x[0])
19 return ans[0:k]