题解 | #字符串出现次数的TopK问题#
字符串出现次数的TopK问题
https://www.nowcoder.com/practice/fd711bdfa0e840b381d7e1b82183b3ee
class Solution:
def topKstrings(self , strings: List[str], k: int) -> List[List[str]]:
# write code here
from functools import cmp_to_key
def compare(x,y):
if x[1]>y[1]:
return -1
elif x[1]==y[1]:
if x[0]<y[0]:
return -1
else:
return 1
else:
return 1
dic = {}
for i in strings:
if i in dic:
dic[i] += 1
else:
dic[i] = 1
li = list(dic.items())
li.sort(key = cmp_to_key(compare))
res = li[:k]
for i in range(len(res)):
res[i] = [res[i][0],res[i][1]]
return res

查看14道真题和解析