题解 | #字符串出现次数的TopK问题#
字符串出现次数的TopK问题
https://www.nowcoder.com/practice/fd711bdfa0e840b381d7e1b82183b3ee
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 // 定一个返回结果集的二维数组 String[][] result = new String[k][2]; if (strings == null || strings.length == 0 || k < 1) { return result; } // 定义个hash,记录字符串出出现的次数 HashMap<String, Integer> hashMap = new HashMap<>(); for (int i = 0; i < strings.length; i ++) { if (hashMap.containsKey(strings[i])) { hashMap.put(strings[i], hashMap.get(strings[i]) + 1); } else { hashMap.put(strings[i], 1); } } // 定一个大顶堆, 自定义比较大小 PriorityQueue<Node> priorityQueue = new PriorityQueue<>(new Comparator<Node>() { @Override public int compare(Node o1, Node o2) { if (o1.num == o2.num) { //字典序小的在前 所以 o1 比 o2 return o1.val.compareTo(o2.val); } else { //数量大的在前所以 o2 - o1 return o2.num - o1.num; } } }); // 将hash中的值放入堆中 for (Map.Entry<String, Integer> value : hashMap.entrySet()) { priorityQueue.offer(new Node(value.getKey(), value.getValue())); } // 将大顶推中的数据存入结果数组中 int i = 0; while (i < k && !priorityQueue.isEmpty()) { Node node = priorityQueue.poll(); String[] temp = new String[2]; temp[0] = node.val; temp[1] = String.valueOf(node.num); result[i] = temp; i ++; } return result; } class Node { String val; int num; Node(String val, int num) { this.val = val; this.num = num; } } }