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

字符串出现次数的TopK问题

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

#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
# return topK string
# @param strings string字符串一维数组 strings
# @param k int整型 the k
# @return string字符串二维数组
#
class Solution:
    def topKstrings(self , strings: List[str], k: int) -> List[List[str]]:
        # write code here
        """
        method1 使用 哈希表
        思路: 建立哈希表,遍历列表,如果字符不在就添加,计数器加1, 之后对val进行排序输出
        步骤:
        step1: 建立哈希
        
        """
        dicts = {}
        counts = 0
        for i in range(len(strings)):
            if strings[i] not in dicts:
                dicts[strings[i]] = 1
            else:
                dicts[strings[i]] += 1
        return (sorted(dicts.items(), key=lambda x:(-x[1], x[0]))[:k])
        pass
		
		先转化为字典
对字典进行排序,排序函数要记住,数字排序时想要按照反序排列可以加一个负号

全部评论

相关推荐

不愿透露姓名的神秘牛友
07-15 17:24
点赞 评论 收藏
分享
06-25 16:25
梧州学院 Java
愿汐_:项目介绍那么长,然而你做了啥就一句话?
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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