Python solution 60ms(beats 95%)


  • 1
    D

    Using defaultdict

    class Solution(object):
        def topKFrequent(self, nums, k):
            """
            :type nums: List[int]
            :type k: int
            :rtype: List[int]
            """
            num_with_count = collections.defaultdict(int)
            for i in nums:
                num_with_count[i] += 1
            sorted_nums = sorted(num_with_count, key=num_with_count.get, reverse=True) 
            return sorted_nums[:k]
    

Log in to reply
 

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