70-Heap--LC692前K个高频单词
作者:互联网
通常在问题中看到 前 K 大,前 KK小 或者 第 K 个, K 个最 等等类似字样,一般情况下我们都可以用堆来做。
class Solution(object):
def topKFrequent(self, words, k):
"""
:type words: List[str]
:type k: int
:rtype: List[str]
"""
# collections.Counter(words)为python自带的计数器
count = collections.Counter(words)
heap = [(-freq, word) for word, freq in count.items()]
heapq.heapify(heap)
return [heapq.heappop(heap)[1] for _ in range(k)]
Todo:这是API实现的,要自己写堆,自己写比较函数
标签:heapq,words,LC692,--,Counter,collections,heap,type,Heap 来源: https://blog.csdn.net/zeronose/article/details/123584165