Simple Python map


  • 1
    D
    class Solution(object):
        def topKFrequent(self, nums, k):
            """
            :type nums: List[int]
            :type k: int
            :rtype: List[int]
            """
            map = {}
            for i in nums:
                if i in map:
                    map[i] = map[i] + 1
                else:
                    map[i] = 1
            #reverse sort by frequency
            l = sorted(map.items(), key=lambda x: x[1], reverse=True)
            return [ x[0] for x in l[:k]] #return the 3 first values
    

Log in to reply
 

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