题解 | #字符串出现次数的TopK问题#

字符串出现次数的TopK问题

http://www.nowcoder.com/practice/fd711bdfa0e840b381d7e1b82183b3ee

class Solution:
    def topKstrings(self , strings: List[str], k: int) -> List[List[str]]:
        # write code here
        if len(strings) == 0: return strings
        
        dic = {}
        for item in strings:
            if item not in dic:
                dic[item] = 1
            else:
                dic[item] += 1
                
        num_dic = {}#反向存dic
        for item in dic:
            if dic[item] not in num_dic:
                num_dic[dic[item]] = item
            else:
                num_dic[dic[item]] += ('.'+item)
        
        Tk = sorted(num_dic,reverse=True)[:k]#顺序存前k大的出现次数值
        
        res = []
        cnt = 0
        for item in Tk:
            for item_ in sorted(num_dic[item].split('.')):
                res.append([item_,item])
                cnt += 1
                if cnt >= k: return res
        return res

全部评论

相关推荐

不愿透露姓名的神秘牛友
06-29 17:30
找实习找着找着就要进入7月了,马上秋招也要开始了,找实习还有意义吗?
绝迹的星:有面就面, 没面上就当日薪4位数大佬免费培训, 面上了再考虑要不要实习
点赞 评论 收藏
分享
06-08 22:25
门头沟学院 Java
从零开始的转码生活:这hr不会打开手机不分青红皂白给所有人群发这句话,过一会再给所有人再发一遍,这肯定会有重复的,不管,再过一会再发一遍
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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