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;
       
    }
}
相关推荐
CQU_JIAKE3 分钟前
3.21【A】
开发语言·php
今儿敲了吗14 分钟前
python基础学习笔记第九章——模块、包
开发语言·python
xyq202420 分钟前
TypeScript 命名空间
开发语言
2301_8101609522 分钟前
C++与物联网开发
开发语言·c++·算法
sxlishaobin25 分钟前
Java I/O 模型详解:BIO、NIO、AIO
java·开发语言·nio
cm65432026 分钟前
基于C++的操作系统开发
开发语言·c++·算法
ArturiaZ29 分钟前
【day57】
开发语言·c++·算法
wjs202431 分钟前
XML 技术
开发语言
彭于晏Yan32 分钟前
Spring AI(二):入门使用
java·spring boot·spring·ai
沪漂阿龙34 分钟前
Python 面向对象编程完全指南:从新手到高手的进阶之路
开发语言·python·microsoft