class Solution: def topKFrequent(self, nums: List[int], k: int) -> List[int]: res=[] num={} for i in nums: if i not in num.keys(): num.update(i=0) num[i]=num[i]+1 topK=zip(num.values(),num.keys()) topList=sorted(topK,key=lambda a:a[0],reverse=True) for j in range(0,k): res.append(topList[j][0]) return res
class Solution3(object): def topKFrequent(self, nums, k): """ :type nums: List[int] :type k: int :rtype: List[int] """ return [key for key, _ in collections.Counter(nums).most_common(k)]
原文:https://www.cnblogs.com/captain-dl/p/10453537.html