题解 | #字符串出现次数的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 先转化为字典 对字典进行排序,排序函数要记住,数字排序时想要按照反序排列可以加一个负号