题解 | #字符串出现次数的TopK问题#
字符串出现次数的TopK问题
http://www.nowcoder.com/practice/fd711bdfa0e840b381d7e1b82183b3ee
看了一圈好像没有python的题解,这里补一个,搬运自:
https://leetcode.com/problems/top-k-frequent-words/discuss/1383677/Python-O(nlogk)-using-priority-queue-and-magic-method。
因为这里要先按count升序再按word降序,所以需要自己实现一个Word类。
最后输出时,逐个将q中的元素pop出来,再取反即可。
# # return topK string # @param strings string字符串一维数组 strings # @param k int整型 the k # @return string字符串二维数组 # class Word: def __init__(self, word=None, count=0): self.word = word self.count = count def __lt__(self, other): if self.count == other.count: return self.word > other.word else: return self.count < other.count from collections import Counter import heapq class Solution: def topKstrings(self , strings , k ): # write code here hm = Counter(strings) q = [] for key, value in hm.items(): heapq.heappush(q, Word(key, value)) if len(q) > k: heapq.heappop(q) res = [] while q: curr = heapq.heappop(q) res.append([curr.word, curr.count]) return res[::-1]