题目1: 一个int数组, 要求结果 1. 去重 2. 统计相同元素重复的次数 3.根据元素重复的次数倒序排列
/**
* 题目1: 一个int数组, 要求结果 1. 去重 2. 统计相同元素重复的次数 3.根据元素重复的次数倒序排列
* <p>
* int[] ints = {9, 8, 7, 6, 5, 10, 100, 1, 3, 0, 1, 9, 5, 6, 3};
* <p>
* key-value,左边是数组元素, 右边是元素统计次数。
* [1=2, 3=2, 5=2, 6=2, 9=2, 0=1, 100=1, 7=1, 8=1, 10=1]
*
*
* 解决这道题的关键就是, 把我hashmap的特性,进行分组,和统计。
*
* 然后借助list排序。
*
*
*/
private static void test_01(int[] ints) {
HashMap<Integer, Integer> hashMap = new HashMap<>();
//分组和计数,借助hashMap实现,
for (int i = 0; i < ints.length; i++) {
//1. hashMap的key时候包含元素, 包含,value+1; 不包含: 添加key=元素, 并且value=1
if (hashMap.containsKey(ints[i])) {
Integer val = hashMap.get(ints[i]);
hashMap.put(ints[i], val + 1);
} else {
hashMap.put(ints[i], 1);
}
}
//list支持排序
ArrayList<Map.Entry<Integer, Integer>> list = new ArrayList<>(hashMap.entrySet());
list.sort(new Comparator<Map.Entry<Integer, Integer>>() {
@Override
public int compare(Map.Entry<Integer, Integer> o1, Map.Entry<Integer, Integer> o2) {
if (o1.getValue() > o2.getValue()) {
return -1;
}
if ((o1.getValue() < o2.getValue())) {
return 1;
}
return 0;
}
});
System.out.println(list);
}