当前位置:网站首页>力扣 215. 数组中的第K个最大元素
力扣 215. 数组中的第K个最大元素
2022-08-02 03:37:00 【熬不了夜哇】
题目
给定整数数组 nums 和整数 k,请返回数组中第 k 个最大的元素。
请注意,你需要找的是数组排序后的第 k 个最大的元素,而不是第 k 个不同的元素。

Java题解
//时间复杂度O(nlogk)
class Solution {
public int findKthLargest(int[] nums, int k) {
//PriorityQueue<Integer> heap=new PriorityQueue<Integer>((n1,n2)->n1-n2);//小根堆
PriorityQueue<Integer> heap=new PriorityQueue<Integer>();//默认小根堆
for(int n:nums){
heap.add(n);//队尾添加元素
if(heap.size()>k)//返回长度大于k时,把最小值(即根结点)删掉,保留当前最大的k个结点
heap.poll();//取出队首元素,(删除)
}
return heap.poll();
}
}Java知识点
PriorityQueue详解 可以处理动态数据流
堆(Heap)分为小根堆和大根堆两种。Min-heap: 父节点的值小于或等于子节点的值;Max-heap: 父节点的值大于或等于子节点的值。
| 方法 | 功能 |
| add(Element e) | 队尾添加元素 |
| clear() | 清空整个列队 |
| contains(Object o) | 检查是否包含当前参数元素,返回布尔类型 |
| offer(E e) | 添加元素 |
| peek() | 访问队首元素(不删除) |
| poll() | 取出队首元素,(删除) |
| remove(Object o) | 根据value删除指定元素 |
| size() | 返回长度 |
| isEmpty() | 判断队列是否为空,返回布尔类型 |
PriorityQueue默认小根堆
PriorityQueue<Integer> heap = new PriorityQueue<>(new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o1 - o2;
}
});PriorityQueue实现大根堆
方法一:重写compare方法
PriorityQueue<Integer> MaxHeap=new PriorityQueue<>(new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o2-o1;
}
});
方法二:lambda表达式
// 1. 不需要参数,返回值为 5 () -> 5 // 2. 接收一个参数(数字类型),返回其2倍的值 x -> 2 * x // 3. 接受2个参数(数字),并返回他们的差值 (x, y) -> x – y // 4. 接收2个int型整数,返回他们的和 (int x, int y) -> x + y // 5. 接受一个 string 对象,并在控制台打印,不返回任何值(看起来像是返回void) (String s) -> System.out.print(s)
PriorityQueue<Integer> MaxHeap=new PriorityQueue<Integer>((n1,n2)->n2-n1);边栏推荐
- arr的扩展方法、数组的遍历及其他方法
- 深蓝学院-手写VIO作业-第一章
- 使用docker-compose 安装Redis最新版,并且设置密码
- ScholarOne Manuscripts提交期刊LaTeX文件,无法成功转换PDF!
- 分布式系统的一致性与共识(1)-综述
- 深蓝学院-手写VIO作业-第二章
- Deep Blue Academy - Visual SLAM Lecture Fourteen - Chapter 5 Homework
- Transfer of UKlog.dat and QQ, WeChat files
- 全球主要国家地区数据(MySQL数据)
- 多主复制的适用场景(2)-需离线操作的客户端和协作编辑
猜你喜欢
随机推荐
从事功能测试1年,裸辞1个月,找不到工作的“我”怎么办?
MapFi paper structure organization
侦听器watch及其和计算属性、methods方法的总结
[Win11] PowerShell无法激活Conda虚拟环境
[Study Notes] How to Create an Operation and Maintenance Organizational Structure
节流阀和本地存储
深蓝学院-视觉SLAM十四讲-第五章作业
Research Notes (8) Deep Learning and Its Application in WiFi Human Perception (Part 2)
WIN10什么都没开内存占用率过高, WIN7单网卡设置双IP
盒子移动和滚动加载效果练习
CaDDN paper reading of monocular 3D target detection
Research Notes (8) Deep Learning and Its Application in WiFi Human Perception (Part 1)
CaDDN代码调试
树莓派4B开机自动挂载移动硬盘,以及遇到the root account is locked问题
CC1101魔幻的收发切换机制
ffmpeg推流USB到rtsp
视觉SLAM十四讲--第13讲 实践:设计SLAM系统(最详细的代码调试运行步骤)
Excel skills daquan
ScholarOne Manuscripts提交期刊LaTeX文件,无法成功转换PDF!
携手推进国产化发展,未来智安与麒麟软件完成兼容互认证





![[Win11] PowerShell cannot activate Conda virtual environment](/img/53/464ffb5ef80ce8f6ee19e9ea96c159.png)



