题解 | #字符串出现次数的TopK问题#
字符串出现次数的TopK问题
http://www.nowcoder.com/practice/fd711bdfa0e840b381d7e1b82183b3ee
Counter统计频数+排序:
from collections import Counter
class Solution:
def topKstrings(self , strings: List[str], k: int) -> List[List[str]]:
# write code here
counter = Counter(strings) # 统计频数
# 按照频数的负数递增(也就是频数递减)排序,频数相等的话按照字典序升序排序,并取前k个
ret = sorted(counter.items(), key=lambda x:[-x[1],x[0]])[:k]
return ret