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;
       
    }
}
相关推荐
油丶酸萝卜别吃2 小时前
utils.js 说明文档
开发语言·javascript·ecmascript
rannn_1114 小时前
【力扣hot100】链表专题|160、206、234、141、142
java·算法·leetcode·链表·面试·开发
leisoo80975 小时前
100GBA股股票数据怎么存ClickHouseRedisMySQLJSON完整对比
大数据·linux·服务器·开发语言·python
不会代码的小猴5 小时前
21. 泛型编程上
开发语言·c++·笔记·算法
IKUN家族6 小时前
Spring IoC&DI
java·spring·rpc
一只旭宝6 小时前
细讲C加加【9】C++ std::function与std::bind详解|仿函数、绑定器、类成员绑定、占位符、成员偏移指针
开发语言·c++·算法
山荷枝7 小时前
03-框架--Spring
java·后端·spring
ChaHae-In8 小时前
SpringBoot统一功能处理
java·spring boot·后端
coder!mq8 小时前
说几个常见的语法糖?
java·开发语言·算法
gugucoding8 小时前
38. 【Java】Stream API(下):高级操作与性能
java·开发语言