在一个数组中找到前K大的数
样例
给出 [3,10,1000,-99,4,100]
, k = 3
.
返回 [1000, 100, 10]
解题思路:
看到取前X大(小)数,使用优先队列即可。
注意这里使用小根堆,大小始终保持K,不断poll最小的数,最终小根堆会只留下前K大的数
由于poll出来的数是由小到大,而题目要求由大到小,所以取数据时记得反取
import java.util.*;
public class Solution {
/**
* @param nums: an integer array
* @param k: An integer
* @return: the top k largest numbers in array
*/
public int[] topk(int[] nums, int k) {
//小根堆
PriorityQueue<Integer> pq = new PriorityQueue<>();
for(int i=0; i<nums.length; i++){
pq.offer(nums[i]);
if(pq.size() > k){
pq.poll();
}
}
int[] res = new int[k];
for(int i=k-1; i>=0; i--)
res[i] = pq.poll();
return res;
}
}