有一个数组,其中有两个数字x,y,找出数组中这两个数字出现次数较多的那个

有一个数组,找出数组中出现次数最多的两个数字

public static void main(String[] args) {
        int[] nums = {1, 3, 2, 1, 3, 2, 4, 3, 4, 4}; // 示例数组
        Map<Integer, Integer> countMap = new HashMap<>();

        // 统计每个数字出现的次数
        for (int num : nums) {
            countMap.put(num, countMap.getOrDefault(num, 0) + 1);
        }

        // 使用优先队列(最大堆)找出出现次数最多的数字
        PriorityQueue<Map.Entry<Integer, Integer>> maxHeap = new PriorityQueue<>(
                (a, b) -> b.getValue() - a.getValue());

        maxHeap.addAll(countMap.entrySet());

        // 如果数组中所有数字都只出现一次,则没有满足条件的数字对
        if (maxHeap.isEmpty()) {
            System.out.println("没有找到出现次数超过一次的数字");
            return;
        }

        // 提取出现次数最多的两个数字
        Map.Entry<Integer, Integer> mostFrequent = maxHeap.poll();
        Map.Entry<Integer, Integer> secondMostFrequent = maxHeap.poll();

        System.out.println("出现次数最多的数字是: " + mostFrequent.getKey()
                + ", 出现了 " + mostFrequent.getValue() + " 次");
        System.out.println("出现次数第二多的数字是: " + secondMostFrequent.getKey()
                + ", 出现了 " + secondMostFrequent.getValue() + " 次");

		// 下面是如果出现了并列的情况
        // 获取最高频率
        int maxFrequency = maxHeap.peek().getValue();

        // 输出所有出现次数最多的数字
        while (!maxHeap.isEmpty() && maxHeap.peek().getValue() == maxFrequency) {
            Map.Entry<Integer, Integer> entry = maxHeap.poll();
            System.out.println("出现次数最多的数字是: " + entry.getKey()
                    + ", 出现了 " + entry.getValue() + " 次");
        }
    }
posted @   fchhk  阅读(3)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示