[LC] 215. Kth Largest Element in an Array
2024-09-04 15:45:26
Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element.
Example 1:
Input:[3,2,1,5,6,4]
and k = 2
Output: 5
Example 2:
Input:[3,2,3,1,2,4,5,5,6]
and k = 4
Output: 4
Note:
You may assume k is always valid, 1 ≤ k ≤ array's length.
Solution 1:
Time: O(NlgN)
class Solution {
public int findKthLargest(int[] nums, int k) {
Arrays.sort(nums);
return nums[nums.length - k];
}
}
Solution 2:
Time: O(Nlgk)
class Solution {
public int findKthLargest(int[] nums, int k) {
if (nums == null || nums.length == 0) {
return 0;
}
PriorityQueue<Integer> pq = new PriorityQueue<>();
for (int num : nums) {
pq.offer(num);
if (pq.size() > k) {
pq.poll();
}
}
return pq.poll();
}
}
最新文章
- camerc文件播放
- boss设计参考的脑图
- Observer - IO (File Monitor)
- poj 2182 树状数组
- Hive 接口介绍(Web UI/JDBC)
- css 横向渐变 图片阴影效果 字体模糊效果
- Chrome/Chromium HTML5 video 视频播放硬件加速
- java学习之反射
- Javaweb开发中URL路径的使用
- 模拟IIC协议时序
- ES6中的export以及import的使用多样性
- cobbler无人值守自动安装
- 基于Python的ModbusTCP客户端实现
- win怎么设置最快捷的下滑关机
- BZOJ 1340: [Baltic2007]Escape逃跑问题
- vscode 本地调试nodejs
- django配置templates、static、media和连接mysql数据库
- APUE学习笔记——5.2流与文件对象、fwide
- File I/O知识点
- 捅伊朗黑客PP — 后台登陆POST+错误回显 注入
热门文章
- 关于阿里云的远程连接和轻型桌面(xfce4)安装
- PROOF|ADOBE READER
- Ubuntu16.04 + ROS下串口通讯
- 使用linux服务器安装wordpress博客详细教程
- Dynamics CRM - 为 Form 或者字段设置 Error Notification
- Python批量重命名文件
- sublime3激活方法
- one_day_one_linuxCmd---wget命令
- Java类只加载一次的情况
- npm安装依赖报 npm ERR! code Z_BUF_ERROR npm ERR! errno -5 npm ERR! zlib: unexpected end of file 这个错误解决方案