import java.util.*; public class Solution { /** * return topK string * @param strings string字符串一维数组 strings * @param k int整型 the k * @return string字符串二维数组 */ public String[][] topKstrings (String[] strings, int k) { //统计每个字符串出现的次数,并对字符串排序 TreeMap<String , Integer> map = new TreeMap<>() ; for(String str : strings) { Integer count = map.get(str) ; if(count == null) { map.put(str , 1) ; } else { map.put(str , count + 1) ; } } //对字符串次数排序,次数相同的的字符串依次放入链表 TreeMap<Integer , ArrayList<String>> mapCount = new TreeMap<>((n1 , n2)->n2-n1) ; for(String key : map.keySet()) { int count = map.get(key) ; ArrayList<String> list = mapCount.get(count) ; if(list == null) { list = new ArrayList<String>() ; list.add(key) ; mapCount.put(count , list) ; } else { list.add(key) ; } } //确定string[][]的真实长度,取 K 和 strings中不重复字符串次数 的最小值 int realK = k < map.size() ? k : map.size() ; String[][] res = new String[realK][2] ; int index = 0 ; //遍历mapCount,填充string[][] for(Integer cnt : mapCount.keySet()) { List<String> list = mapCount.get(cnt) ; for(int i = 0 ; i < list.size() && index < realK; i ++) { res[index][0] = list.get(i) ; res[index ++][1] = String.valueOf(cnt) ; } if(index == realK) break ; } return res ; } }