LeetCode 692. [Python] Top K Frequent Words
原题链接
中等
作者:
徐辰潇
,
2021-09-26 22:27:13
,
所有人可见
,
阅读 307
class element:
def __init__(self, freq, word):
self.freq = freq
self.word = word
def __lt__(self, Element):
if self.freq == Element.freq:
return self.word > Element.word
else:
return self.freq < Element.freq
class Solution:
def topKFrequent(self, words: List[str], k: int) -> List[str]:
Dict = {}
for word in words:
Dict[word] = Dict.get(word,0) + 1
PQ = []
for word in Dict.keys():
Element = element(Dict[word], word)
if len(PQ) < k:
heapq.heappush(PQ, Element)
else:
if PQ[0].__lt__(Element):
heapq.heappop(PQ)
heapq.heappush(PQ, Element)
res = []
while len(PQ):
res.append(PQ[0].word)
heapq.heappop(PQ)
return res[::-1]