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;
}
}