出现次数为topK的问题
出现次数的TopK问题
http://www.nowcoder.com/questionTerminal/fd711bdfa0e840b381d7e1b82183b3ee
用Java的小根堆进行排序
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 || strings.length == 0)
return new String[0][0];
//统计每个数字出现的次数
Map<String, Integer> countMap = new HashMap<>();
for(String str : strings){
countMap.put(str, countMap.getOrDefault(str,0)+1);
}
//建立大小为k的小根堆
//w1表示要添加进来的数,w2表示堆头
PriorityQueue<String> heap = new PriorityQueue<String>(
(w1, w2) -> countMap.get(w1).equals(countMap.get(w2)) ?
w2.compareTo(w1) : countMap.get(w1) - countMap.get(w2) );
for(String str : countMap.keySet()){
//会按照定义的去排序,跟堆头比较
heap.offer(str);
//poll方法是poll出堆头,把最小的去掉,再把最小的一位放在堆头
if(heap.size() > k) heap.poll();
}
String[][] res = new String[k][2];
int idx = k-1;
while(!heap.isEmpty()){
String temp = heap.poll();
res[idx][0] = temp;
res[idx][1] = countMap.get(temp) + "";
idx--;
}
return res;
}
}
查看30道真题和解析