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;
       
    }
}
相关推荐
zhangkaixuan4561 天前
Apache Paimon 查询全流程深度分析
java·apache·paimon
cici158741 天前
MyBatis注解的运用于条件搜索实践
java·tomcat·mybatis
wangqiaowq1 天前
StarRocks安装部署测试
java·开发语言
计算机学姐1 天前
基于SpringBoot的高校社团管理系统【协同过滤推荐算法+数据可视化】
java·vue.js·spring boot·后端·mysql·信息可视化·推荐算法
缺点内向1 天前
C#: 高效移动与删除Excel工作表
开发语言·c#·.net·excel
工业甲酰苯胺1 天前
实现 json path 来评估函数式解析器的损耗
java·前端·json
老前端的功夫1 天前
Web应用的永生之术:PWA落地与实践深度指南
java·开发语言·前端·javascript·css·node.js
@forever@1 天前
【JAVA】LinkedList与链表
java·python·链表
LilySesy1 天前
ABAP+WHERE字段长度不一致报错解决
java·前端·javascript·bug·sap·abap·alv
六件套是我1 天前
redission实现延时队列
android·java·servlet