Top K frequent words
这个题早该出现了,直接用堆统计就行了
class Solution(object):
def topKFrequent(self, words, k):
"""
:type words: List[str]
:type k: int
:rtype: List[str]
"""
store = collections.Counter()
for word in words:
store[word] += 1
result = []
heap = []
for key, value in store.iteritems():
heapq.heappush(heap, (-value, key), )
while k:
result.append(heapq.heappop(heap)[1])
k -= 1
return result