题解 | #求二叉树的层序遍历#
字符串出现次数的TopK问题
http://www.nowcoder.com/practice/fd711bdfa0e840b381d7e1b82183b3ee
使用map存放相关的字符串和计数
然后使用list 对map的entry进行排序 取出前k个就可以了;
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
Map<String,Integer> map=new HashMap<String,Integer>();
for(String str: strings){
map.put(str,map.getOrDefault(str,0)+1);
}
List<Map.Entry<String,Integer>> infos = new ArrayList<Map.Entry<String,Integer>>(map.entrySet());
Collections.sort(infos, new Comparator<Map.Entry<String,Integer>>(){
public int compare(Map.Entry<String,Integer> str1, Map.Entry<String,Integer> str2) {
if(str1.getValue()==str2.getValue()) return str1.getKey().compareTo(str2.getKey());
else return str2.getValue()-str1.getValue();
}
});
String[][] topKstrings=new String[k][2];
int c=0;
for(Map.Entry<String,Integer> entry:infos){
String num = String.valueOf(entry.getValue());
topKstrings[c][0]=entry.getKey();
topKstrings[c][1]=num;
c++;
if(c==k){
break;
}
}
return topKstrings;
}
}