Python solution use collections.Counter


  • 0
    B
    class Solution(object):
        def topKFrequent(self, nums, k):
            """
            :type nums: List[int]
            :type k: int
            :rtype: List[int]
            """
            # use collections.Counter
            from collections import Counter
            res = []
            for key,val in Counter(nums).most_common(k):
                res.append(key)
            return res

  • 0
    M

    You can make it shorter.

    def topKFrequent(self, nums, k):
        return [ c for c, _ in collections.Counter(nums).most_common(k) ]
    

  • 0
    B

    @musteryu yeah,excellent!


Log in to reply
 

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