排序面试题

题目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);


    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值