美文网首页
Kth and Top k

Kth and Top k

作者: SharlotteZZZ | 来源:发表于2018-11-07 23:27 被阅读0次

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

      本文链接:https://www.haomeiwen.com/subject/qkjpzftx.html