-
Notifications
You must be signed in to change notification settings - Fork 0
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
【Day 85 】2024-02-08 - 215. 数组中的第 K 个最大元素 #89
Comments
|
1 similar comment
|
利用priority queue的data structure, 每次保留目前遍历过中最大的k个数字. 然后在iterate through整个array之后, 自然就留下了最大的k个数字. 之后利用优先队列的数据结构, 第一个是kth largest element. 思路参考题解 class Solution {
public int findKthLargest(int[] nums, int k) {
PriorityQueue<Integer> pq = new PriorityQueue<>();
for(int i = 0; i< nums.length; i++){
pq.add(nums[i]);
if(pq.size()> k){
pq.poll();
}
}
return pq.peek();
}
} 时间复杂度: O(n)? # n是nums.length 空间复杂度: O(n) |
class Solution {
}; |
|
思路大顶堆 代码class Solution {
public int findKthLargest(int[] nums, int k) {
//大顶堆
PriorityQueue<Integer> queue = new PriorityQueue<>((o1, o2) -> o1-o2);
for (int i = 0; i < nums.length; i++) {
queue.offer(nums[i]);
if (queue.size()>k){
queue.poll();
}
}
return queue.peek();
}
} 复杂度
|
215. 数组中的第 K 个最大元素
入选理由
暂无
题目地址
https://leetcode-cn.com/problems/kth-largest-element-in-an-array/
前置知识
题目描述
The text was updated successfully, but these errors were encountered: