题解 | #字符串出现次数的TopK问题#
字符串出现次数的TopK问题
http://www.nowcoder.com/practice/fd711bdfa0e840b381d7e1b82183b3ee
package org.example.test; import com.alibaba.fastjson.JSONObject; import java.util.*; public class TopKstringsTest { public static void main(String[] args) { String[] test = {"a", "b", "c", "b"}; System.out.println(JSONObject.toJSONString(topKstrings(test, 2))); } /** * 搞半天,没有灵活运用list排序和map.get() * @param strings * @param k * @return */ public static String[][] topKstrings(String[] strings, int k) { // write code here SortedMap<String, Integer> map = new TreeMap<>(); for (String str : strings) { map.put(str, map.getOrDefault(str, 0) + 1); } List<String> rec = new ArrayList<String>(); for (Map.Entry<String, Integer> entry : map.entrySet()) { rec.add(entry.getKey()); } Collections.sort(rec, new Comparator<String>() { @Override public int compare(String o1, String o2) { return map.get(o1) == map.get(o2) ? o1.compareTo(o2) : map.get(o2) - map.get(o1); } }); int i = 0; String[][] topk = new String[k][2]; for (String key : rec) { if (i >= k) { break; } topk[i][0] = key; topk[i][1] = String.valueOf(map.get(key)); i++; } return topk; } }
算法 文章被收录于专栏
数据结构和算法