347. Top K Frequent Elements

题目来源:
 
自我感觉难度/真实难度:
 
题意:
 
分析:
 
自己的代码:
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