【数据结构与算法】treemap应用 排序

来源:互联网 发布:交换机网络配置 编辑:程序博客网 时间:2024/06/08 00:38

给一个数组,按照出现次数排序,如果出现相同次数,那么按照大小排序。

public static void main(String[] args) {int[] array = {5,10,52,2,2};int[] r = sort(array);for(int i : r){System.out.println(i);}}public static int[] sort(int[] array){int[] r = new int[array.length];int index = 0;Map<Integer, Integer> map = new HashMap<>();for(int i = 0; i < array.length; i++)map.put(array[i], map.getOrDefault(array[i], 0) + 1);TreeMap<Integer, List<Integer>> count = new TreeMap<>();for(Entry<Integer, Integer> entry : map.entrySet()){int c = entry.getValue();if(!count.containsKey(c))count.put(c, new ArrayList<>());count.get(c).add(entry.getKey());}while(!count.isEmpty()){int c = count.lastKey();List<Integer> l = count.get(c);Collections.sort(l);for(int i : l){for(int j = 0; j < c; j++){r[index++] = i;}}count.remove(c);}return r;}


原创粉丝点击