1 import collections 2 import operator 3 def topKFrequent( nums, k): 4 """ 5 :type nums: List[int] 6 :type k: int 7 :rtype: List[int] 8 """ 9 10 d = collections.Counter(nums) 11 target_list = [] 12 soted_freq = sorted(list(d.items()), key=operator.itemgetter(1), reverse=True) 13 for i in range(k): 14 target_list.append(soted_freq[i][0]) 15 return target_list
看到网上有个更简便的
1 from collections import Counter 2 import heapq 3 4 class Solution(object): 5 def topKFrequent(self, nums, k): 6 c = Counter(nums) 7 return heapq.nlargest(k, c, key=lambda x:c[x])