题解 | #字符串出现次数的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

全部评论

相关推荐

10-29 15:51
嘉应学院 Java
后端转测开第一人:你把简历的学历改成北京交通大学 去海投1000份发现基本还是没面试
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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