Share my python solution with explanation


  • 0
    class Solution(object):
    def topKFrequent(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: List[int]
        """
        #nums=sorted(nums,reverse=True)
        dic={}
        for i in nums:
            if i in dic:
                dic[i]+=1
            else:
                dic[i]=1
        dic=sorted(dic.iteritems(),key=lambda x:x[1],reverse=True)#sort the dict according to the value of dict
        res=[item[0] for item in dic]#get the sorted result from numbers of each elements
        return res[:k]

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.