题解 | #字符串出现次数的TopK问题#
字符串出现次数的TopK问题
http://www.nowcoder.com/practice/fd711bdfa0e840b381d7e1b82183b3ee
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) {
// write code here
if(k==0){
return new String[][]{};
}
String[][] res =new String[k][2];
TreeMap<String,Integer> map=new TreeMap<>();
//统计各个字符串出现的次数
for(int i=0;i<strings.length;++i){
String s=strings[i];
if(!map.containsKey(s)){
map.put(s,1);
}else{
map.put(s,map.get(s)+1);
}
}
ArrayList<Map.Entry<String,Integer>> list=new ArrayList<>(map.entrySet());
Collections.sort(list,
(o1, o2) ->
(o1.getValue().compareTo(o2.getValue()) ==
0 ? o1.getKey().compareTo(o2.getKey()) :
o2.getValue().compareTo(o1.getValue()))
);
for (int i = 0; i < k; i++) {
res[i][0] = list.get(i).getKey();
res[i][1] = String.valueOf(list.get(i).getValue());
}
return res;
}
}