-
时间复杂度:,遍历统计为,但是降序排序需要
-
空间复杂度:,使用hashmap辅助结构。
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 if (k == 0)return new String[][]{}; String[][] res = new String[k][2]; Map<String,Integer> map=new HashMap<>(); for(int i=0;i<strings.length;i++){ if(map.containsKey(strings[i])){ map.put(strings[i],map.get(strings[i])+1); }else{//这里的else一定要 不然下面的语句一定执行 map.put(strings[i],1); } } //如何在map中取k个value最大值 ArrayList<Map.Entry<String, Integer>> list =new ArrayList<>(map.entrySet()); Collections.sort(list,(o1, o2) ->(o1.getValue().compareTo(o2.getValue()) ==0 ? o1.getKey().compareTo(o2.getKey()) :o2.getValue().compareTo(o1.getValue()))); for (int i = 0; i < k; i++) { res[i][0] = list.get(i).getKey(); res[i][1] = String.valueOf(list.get(i).getValue()); } return res; } }所以本题可以提供一个模板思路,如何在map中取出前k个最大value值。
思路如下:
1.在List中添加一个Map.Entry<String,Integer>类型的数据
ArrayList<Map.Entry<String, Integer>> list =new ArrayList<>(map.entrySet());
2.先是按出现次数降序比较,相同则再按照字符ASCII码降序比较。
Collections.sort(list,(o1, o2) ->(o1.getValue().compareTo(o2.getValue()) ==0 ? o1.getKey().compareTo(o2.getKey()) :o2.getValue().compareTo(o1.getValue())));
不同的要求有不同的写法。如果只需要降序排列的话:
Collections.sort(list,(o1, o2) ->o2.getValue().compareTo(o1.getValue()));
3.遍历取出