题解 | #字符串出现次数的TopK问题#
字符串出现次数的TopK问题
http://www.nowcoder.com/practice/fd711bdfa0e840b381d7e1b82183b3ee
package suanfa.string;
import java.util.*;
public class TopKstrings {
public static void main(String[] args) {
String[] s = new String[]{"a", "b", "a"};
List<MyNode> list = topKstrings(s, 2);
}
public static List<MyNode> topKstrings(String[] strings, int k) {
Map<String, Integer> map = new HashMap<>();
for (int i = 0; i < strings.length; i++) {
map.put(strings[i], map.getOrDefault(strings[i], 0) + 1);
}
PriorityQueue<MyNode> queue = new PriorityQueue<>(Comparator.comparingInt(o -> o.num));
for (Map.Entry<String, Integer> entry : map.entrySet()) {
MyNode node = new MyNode(entry.getKey(), entry.getValue());
if (queue.size() < k) {
queue.offer(node);
} else {
MyNode tmp = queue.peek();
if (tmp.num < node.num) {
queue.poll();
queue.offer(node);
}
}
}
List<MyNode> list = new ArrayList<>();
while (queue.size() > 0) {
list.add(queue.poll());
}
return list;
}
static class MyNode {
String val;
Integer num;
MyNode(String val, int num) {
this.num = num;
this.val = val;
}
}}