2025年--Lc200- 414. 第三大的数(大根堆)--Java版

1.题目

2.思路

1.小根堆(按自然顺序,越小优先级越高)。

java 复制代码
Queue<Integer> pq = new PriorityQueue<>();

2.(a, b) -> Integer.compare(b, a) 的含义

Integer.compare(x, y):x<y 返回负数;x==y 返回0;x>y 返回正数。

你写的是 compare(b, a)(把参数反过来),等价于"降序比较",因此会让大的数排在前面,得到的是大根堆。

java 复制代码
Queue<Integer> pq = new PriorityQueue<>((a, b) -> Integer.compare(b, a)); // 大根堆

等价写法:

java 复制代码
Queue<Integer> pq = new PriorityQueue<>(Collections.reverseOrder()); // 大根堆
java 复制代码
Queue<Integer> maxHeap = new PriorityQueue<>((a, b) -> Integer.compare(b, a));
maxHeap.offer(5);
maxHeap.offer(1);
maxHeap.offer(3);
System.out.println(maxHeap.poll()); // 5
System.out.println(maxHeap.poll()); // 3
System.out.println(maxHeap.poll()); // 1

(3)数组长度 ≥ 3 也可能没有"第 3 大的不同数字"。

当 set.size()==3 时才会 return x,如果全程都达不到 3 个不同值,就不会提前返回。

nums = 1, 2, 2

不同数字只有 {1,2} 两个,循环结束 set.size() 也只有 2,没法在循环内返回"第三大"。末尾只能返回最大值 2(也就是 max)。

nums = 5, 5, 5, 4

不同数字 {5,4} 也只有 2 个,同理循环里不会触发 set.size()==3,最后返回最大值 5。

3.代码实现

java 复制代码
class Solution {
    public int thirdMax(int[] nums) {
        //用小根堆排序,利用set集合去重
        int n=nums.length;
        if(n==1) return nums[0];
        if(n==2)
        {
            if(nums[0]<nums[1])
            {
                return nums[1];
            }else
            {
                return nums[0];
            }
        }

        //初始化小根堆
        Queue<Integer> ma=new PriorityQueue<>((a,b)->Integer.compare(b,a));
         //数组所有元素放入堆
            for(int num:nums)
            {
                ma.add(num);
            }
            //记录最大值
            int max=ma.peek();
            HashSet<Integer> set=new HashSet<>();
            while(!ma.isEmpty())
            {
                int x=ma.poll();//弹出堆顶元素;
                set.add(x);
                if(set.size()==3) return x;
            }
           //如果未提前返回说明没有第三大的数,返回最大值
           return max;
       
    }
}
相关推荐
吃饱了得干活3 小时前
Spring Cloud Gateway 微服务网关:路由、断言、过滤器
java·spring cloud
lwx572804 小时前
探秘InnoDB:搞懂它的内存、线程、磁盘与日志刷盘策略
java·后端
Flynt6 小时前
从Spring Boot 4.0升到4.1,我在Maven和gRPC上栽了跟头
java·spring boot·后端
plainGeekDev7 小时前
Activity 间传值 → Navigation 参数
android·java·kotlin
plainGeekDev7 小时前
onActivityResult → ActivityResult API
android·java·kotlin
Sunia7 小时前
《AgentX 专栏》10-生产部署:3台2C4G云服务器把企业级Agent真正跑起来的完整方案
java·架构
ZhengEnCi8 小时前
J7A-高级Java工程师面试三道灵魂拷问-深度广度与工程素养的终极检验
java·后端
狼爷1 天前
吃透 Java Function 接口,搞定 99% 的 Stream 场景
java·函数式编程
祎雪双十Gy1 天前
从 DataX 的配置加载说起:我用 FastJson2 做了一个轻量级动态配置管理库
java·后端
小锋java12341 天前
分享一套锋哥原创的SpringBoot4+Vue3宠物领养网站系统
java