当前位置:网站首页>力扣 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);
边栏推荐
- 剩余参数、数组对象的方法和字符串扩展的方法
- samba,nfs,iscsi网络文件系统
- [Study Notes] How to Create an Operation and Maintenance Organizational Structure
- The slave I/O thread stops because master and slave have equal MySQL server ids
- Jetson Nano 2GB Developer Kit 安装说明
- Win8.1下QT4.8集成开发环境的搭建
- 复制延迟案例(3)-单调读
- Transfer of UKlog.dat and QQ, WeChat files
- 七分钟深入理解——卷积神经网络(CNN)
- 腾讯云+keepalived搭建云服务器主备实践
猜你喜欢
如何将PDF中的一部分页面另存为新的PDF文件
ffmpeg视频播放、格式转化、缩放等命令
吴恩达机器学习系列课程笔记——第九章:神经网络的学习(Neural Networks: Learning)
VisibleDeprecationWarning: Creating an ndarray from ragged nested sequences (which is a list-or-tupl
生物识别学习资源推荐
吴恩达机器学习系列课程笔记——第十三章:聚类(Clustering)
侦听器watch及其和计算属性、methods方法的总结
【学习笔记】如何打造运维组织架构
[Win11] PowerShell无法激活Conda虚拟环境
Class ‘PHPWord_Writer_Word2003‘ not found
随机推荐
this指向问题
SCI期刊最权威的信息查询步骤!
温暖的世界
单目3D目标检测之入门
全球主要国家地区数据(MySQL数据)
Win8.1下QT4.8集成开发环境的搭建
侦听器watch及其和计算属性、methods方法的总结
树莓派上QT连接海康相机
PHP将字符切割成每个拼音
v-bind动态绑定
无主复制系统(2)-读写quorum
Deep Blue Academy-Visual SLAM Lecture 14-Chapter 6 Homework
【学习笔记】如何打造运维组织架构
LVS+Keepalived实现高可用的负载均衡
Scientific research notes (5) SLAC WiFi Fingerprint+ Step counter fusion positioning
Research Notes (6) Indoor Path Planning Method Based on Environment Perception
科研笔记(七) 基于路径规划和WiFi指纹定位的多目的地室内导航
The most authoritative information query steps for SCI journals!
三维目标检测之ROS可视化
基于sysbench工具的压力测试---MyCat2.0+MySql架构