Kth and Top k

Catalog:
[骨骼清奇]LC 692 Top K Frequent Words
[骨骼清奇]LC 347 Top K Frequent Element
[Uber]414Third Maximum Number

LC 692 Top K Frequent Words

    def topKFrequent(self, words, k):
        d = {}
        for word in words:
            d[word] = d.get(word, 0) + 1
        
        ret = sorted(d, key=lambda word: (-d[word], word))
        
        return ret[:k]

First, we have a frequency Counter, then we could do
(1)Heap: pushing onto min-heap, pop when size >K
(2)bucket sort: dict of list, key is freq and value is list of words, if it is integer, we can just output it key times!

LC 347 Top K Frequent Element
Input: nums = [1,1,1,2,2,3], k = 2
Output: [1,2]

你可能感兴趣的:(Kth and Top k)