这道题我们先用heap做了,之后再用排序的方法处理。
public class Solution {
public int findKthLargest(int[] nums, int k) {
PriorityQueue<Integer> queue = new PriorityQueue<>();
for (int i : nums) {
queue.offer(i);
if (queue.size() > k) {
queue.poll();
}
}
return queue.peek();
}
}
本文介绍了一种使用最小堆解决寻找数组中第K大的元素的问题。通过维护一个大小为K的最小堆,可以有效地找到目标元素。该方法优于直接排序,在大数据集上表现更佳。
260

被折叠的 条评论
为什么被折叠?



