Python Bucket Sort


  • 0

    Same idea as Top K elements

    class Solution(object):
        def topKFrequent(self, words, k):
            """
            :type words: List[str]
            :type k: int
            :rtype: List[str]
            """
            d = collections.defaultdict(int)
            for word in words:
                d[word] += 1
            bucket = [[] for _ in range(len(words) + 1)]
            for key in d:
                bucket[d[key]].append(key)
            res = []
            for i in reversed(range(len(words) + 1)):
                if len(res) >= k:
                    break
                if len(bucket[i]) > 0:
                    bucket[i].sort()
                    if len(bucket[i]) + len(res) <= k:
                        res += bucket[i]
                    else:
                        res += bucket[i][:k - len(res)]
            return res
    

Log in to reply
 

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