692. Top K Frequent Words
看到O(n*logk) 就想到heap了,本来想只维护一个长度为k的堆,但因为次数相同要遵照字母顺序,怎么都写不对,还是得用大根堆,对整个list做了堆排序。
class Solution:
def topKFrequent(self, words: List[str], k: int) -> List[str]:
freq = [(-count, word) for word, count in collections.Counter(words).items()]
heapq.heapify(freq)
res = []
for _ in range(k):
res.append(heapq.heappop(freq)[1])
return res
可以 sort 来做,非常 pythonized:
class Solution:
def topKFrequent(self, words: List[str], k: int) -> List[str]:
return [sorted(collections.Counter(words).items(), key=lambda x:(-x[1], x))[i][0] for i in range(k)]
Last updated
Was this helpful?