My O(n) Python solution, using bucket


  • 0
    X
    def topKFrequent(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: List[int]
        """
        if len(nums) < k:
            return []
            
        frequency = collections.Counter(nums)
        bucket = collections.defaultdict(list)
        for key in frequency:
            f = frequency[key]
            bucket[f].append(key)
        res = []
        count = len(nums) # the upper limit for res
        while len(res) < k:
            if bucket[count]:
                res += bucket[count]
            count -= 1
        return res

Log in to reply
 

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