题解 | #字符串出现次数的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]
全部评论

相关推荐

牛客266927136号:为啥实习经历写这么少,项目经历反而大写特写,最重要的还是实习经历吧,写具体点,什么场景下做了什么事,解决了什么问题,优化了什么场景,性能提升了多少多少
点赞 评论 收藏
分享
牛客383479252号:9,2学生暑期实习失利开始投小厂,给这群人整自信了
点赞 评论 收藏
分享
06-25 16:00
武汉大学 Java
工科研究生底薪工资就开3k啊??
机械打工仔:写文章提成的岗位工资低,你怪工科?
点赞 评论 收藏
分享
评论
2
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务