题解 | #字符串出现次数的TopK问题#
字符串出现次数的TopK问题
http://www.nowcoder.com/practice/fd711bdfa0e840b381d7e1b82183b3ee
利用PriorityQueue实现一个大顶堆,用map记录好每个字符出现的次数,然后将map的数据导入大顶堆,然后从大顶堆弹出,记录在String[][],然后返回,,利用大顶堆整理顺序。
import java.util.*;
public class Solution {
/**
* return topK string
* @param strings string字符串一维数组 strings
* @param k int整型 the k
* @return string字符串二维数组
*/
class Tuple implements Comparable<Tuple>{
String name;
int index;
public Tuple(String n,int i){
this.name = n;
this.index = i;
}
public int compareTo(Tuple t){
if(this == t){
return 0;
}
if(this.index != t.index){
return -(this.index - t.index);
}else{
return this.name.compareTo(t.name);
}
}
}
public String[][] topKstrings (String[] strings, int k) {
// write code here
String[][] res = new String[k][2];
if(strings.length == 0 || k == 0){
return res;
}
HashMap<String,Integer> hm = new HashMap<>();
for(String s : strings){
if(hm.containsKey(s)){
int flag = hm.get(s) + 1;
hm.put(s,flag);
}else{
hm.put(s,1);
}
}
PriorityQueue<Tuple> p = new PriorityQueue<>();
for(HashMap.Entry<String,Integer> h : hm.entrySet()){
p.offer(new Tuple(h.getKey(),h.getValue()));
}
for(int i = 0;i<k;i++){
Tuple x = p.poll();
res[i][0] = x.name;
res[i][1] = String.valueOf(x.index);
}
return res;
}
}