leetcode 215. Kth Largest Element in an Array

时间:2023-11-25 18:19:56

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.

For example,
Given [3,2,1,5,6,4] and k = 2, return 5.

Note: 
You may assume k is always valid, 1 ≤ k ≤ array's length.

题意:

给出一个未排序的数组,找出数组中第K大的元素。

方法:

使用优先级队列来解决。

优先级队列是不同于先进先出队列的另一种队列,每次从队列中取出的是具有最高优先权的元素。

如果不是提供comparator的话,优先队列中的元素默认按照自然顺序排列,

也就是数字小的默认在队列头,字符串按照字典顺序排列。

public class Solution {
//优先队列,
//遍历数组时将数字加入优先队列(堆),一旦堆的大小大于k就将堆顶元素去除,
//确保堆的大小为k,
public int findKthLargest(int[] nums, int k) {
PriorityQueue<Integer> p = new PriorityQueue<Integer>();
for(int i=0; i<nums.length;i++){
p.add(nums[i]);
if(p.size()>k) p.poll();
}
return p.poll(); }
}