1.使用HashMap统计每个字符串出现次数
2.使用优先队列存入map中的entry并进行自定义排序
3.依次输出优先队列中的前k个entry存入结果中
import java.util.*;
public class Solution {
public String[][] topKstrings (String[] strings, int k) {
HashMap<String,Integer> map = new HashMap();
for(String s:strings){
map.put(s,map.getOrDefault(s,0)+1);
}
PriorityQueue<Map.Entry<String,Integer>> pq = new PriorityQueue<>((a, b)->{
if(a.getValue().compareTo(b.getValue())==0){
return a.getKey().compareTo(b.getKey());
}else{
return b.getValue()-a.getValue();
}
});
for(Map.Entry<String,Integer> entry:map.entrySet()){
pq.offer(entry);
}
String[][] res = new String[k][2];
for(int i = 0;i<k;i++){
Map.Entry<String,Integer> entry = pq.poll();
res[i][0] = entry.getKey();
res[i][1] = String.valueOf(entry.getValue());
}
System.out.println("9".compareTo("1"));
return res;
}
}