题解 | #序列和#
字符串出现次数的TopK问题
http://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 // 15:11 TreeMap<String,Integer> map = new TreeMap<>(); for(int i=0;i<strings.length;i++){ map.put(strings[i],map.getOrDefault(strings[i],0)+1); } // 排序 ArrayList<Map.Entry<String,Integer>> list = new ArrayList<>(map.entrySet()); Collections.sort(list,new Comparator<Map.Entry<String,Integer>>(){ @Override public int compare(Map.Entry<String,Integer> o1,Map.Entry<String,Integer> o2){ if(o1.getValue().equals(o2.getValue())){ return o1.getKey().compareTo(o2.getKey()); }else{ return o2.getValue().compareTo(o1.getValue()); } } }); String[][] res = new String[k][2]; for(int i=0;i<k;i++){ res[i][0] = new String(list.get(i).getKey()); res[i][1] = new String(String.valueOf(list.get(i).getValue())); } return res; } }
这是借用treeMap的排序做的,不知道算不算?