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