地址:https://www.nowcoder.com/practice/fd711bdfa0e840b381d7e1b82183b3ee?tpId=188&&tqId=38637&rp=1&ru=/activity/oj&qru=/ta/job-code-high-week/question-ranking
1 ''' 2 描述 3 给定一个字符串数组,再给定整数k,请返回出现次数前k名的字符串和对应的次数。 4 返回的答案应该按字符串出现频率由高到低排序。如果不同的字符串有相同出现频率,按字典序排序。 5 对于两个字符串,大小关系取决于两个字符串从左到右第一个不同字符的 ASCII 值的大小关系。 6 比如"ah1x"小于"ahb","231"<”32“ 7 字符仅包含数字和字母 8 9 [要求] 10 如果字符串数组长度为N,时间复杂度请达到O(N log K)O(NlogK) 11 12 示例1 13 输入: 14 ["a","b","c","b"],2 15 复制 16 返回值: 17 [["b","2"],["a","1"]] 18 说明: 19 "b"出现了2次,记["b","2"],"a"与"c"各出现1次,但是a字典序在c前面,记["a","1"],最后返回[["b","2"],["a","1"]] 20 21 示例2 22 输入: 23 ["123","123","231","32"],2 24 返回值: 25 [["123","2"],["231","1"]] 26 说明: 27 "123"出现了2次,记["123","2"],"231"与"32"各出现1次,但是"231"字典序在"32"前面,记["231","1"],最后返回[["123","2"],["231","1"]] 28 29 ''' 30 31 ''' 32 1.先计数并存转成list格式 33 2.先按照 出现数字降序 再按照字符升序排序 34 ''' 35 36 # 37 # return topK string 38 # @param strings string字符串一维数组 strings 39 # @param k int整型 the k 40 # @return string字符串二维数组 41 # 42 class Solution: 43 def topKstrings(self , strings , k ): 44 # write code here 45 res = {} 46 for i in strings: 47 if i not in res.keys(): 48 res[i] = 1 49 else: 50 res[i] +=1 51 resList = [] 52 for i in res.keys(): 53 resList.append([i,res[i]]) 54 resList.sort(key=lambda i : (-i[1],i[0])) 55 return resList[:k]