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) { PriorityQueue pq = new PriorityQueue<>(); HashMap<String, Integer> strTimesMap = new HashMap<>(); for (int i = 0; i < strings.length; i++) { strTimesMap.put(strings[i], strTimesMap.getOrDefault(strings[i],0) + 1); } for (Map.Entry<String, Integer> entry : strTimesMap.entrySet()){ Node cur = new Node(entry.getKey(), entry.getValue()); if (pq.size() < k){ pq.add(cur); }else{ if (pq.peek().compareTo(cur) < 0){ pq.poll(); pq.add(cur); } } } String[][] res = new String[k][2]; for (int i = k - 1; i >= 0; i--){ Node e = pq.poll(); res[i][0] = e.value; res[i][1] = String.valueOf(e.times); } return res; } } class Node implements Comparable { String value; int times;
public Node(String value, int times) {
this.value = value;
this.times = times;
}
@Override
public int compareTo(Node o) {
if (this.times == o.times){
return o.value.compareTo(this.value);
}
return this.times - o.times;
}
}