方法一:哈希表+数组排序
public String[][] topKstrings (String[] strings, int k) { // write code here if (strings == null || strings.length == 0){ return null; } HashMap<String, Integer> map = new HashMap<>(); for (String string : strings) { map.put(string,map.getOrDefault(string,0)+1); } String[][] temp = new String[map.keySet().size()][2]; int i = 0; for (String s : map.keySet()) { temp[i][0] = map.get(s) + ""; temp[i++][1] = s; } Arrays.sort(temp, new Comparator<String[]>() { @Override public int compare(String[] o1, String[] o2) { if (Integer.valueOf(o1[0]) > Integer.valueOf(o2[0])){ return -1; }else if (Integer.valueOf(o1[0]) == Integer.valueOf(o2[0])){ return o1[1].compareTo(o2[1]); }else { return 1; } } }); System.out.println(Arrays.deepToString(temp)); String[][] res = new String[k][2]; for (int i1 = 0; i1 < k; i1++) { res[i1][0] = temp[i1][1]; res[i1][1] = temp[i1][0]; } return res; }
方法二:哈希表+堆排序
PriorityQueue是java.util包里的一个优先队列,底层是一个小根堆,但是我们可以在创建一个优先队列的时候,传入一个自定义的比较器对象,让其变为大根堆。这样,我们将通过哈希表统计出来的字符串及其出现的频次封装成一个pair对象,然后放入大根堆中,直接让优先队列出队k次即可。
import java.util.*; import java.util.Arrays; import java.util.Comparator; import java.util.HashMap; import java.util.PriorityQueue; 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 (strings == null || strings.length == 0) { return null; } HashMap<String, Integer> map = new HashMap<>(); for (String string : strings) { map.put(string, map.getOrDefault(string, 0) + 1); } PriorityQueue<Pair<String, Integer>> heap = new PriorityQueue<>(new Comparator<Pair<String, Integer>>() { @Override public int compare(Pair<String, Integer> o1, Pair<String, Integer> o2) { if (o1.getValue().compareTo(o2.getValue()) == 1) { return -1; } else if (o1.getValue().compareTo(o2.getValue()) == 0) { return o1.getKey().compareTo(o2.getKey()); } else { return 1; } } }); for (String s : map.keySet()) { heap.add(new Pair<String, Integer>(s,map.get(s))); } String[][] res = new String[k][2]; for (int i = 0; i < k; i++) { Pair<String, Integer> curNode = heap.poll(); res[i][0] = curNode.getKey(); res[i][1] = curNode.getValue()+""; } return res; } } class Pair<K,V>{ private K key; private V value; public Pair(K k,V v){ this.key = k; this.value = v; } public K getKey() { return key; } public V getValue() { return value; } }