Given an integer array, find the top k largest numbers in it.
Example
Example1
Input: [3, 10, 1000, -99, 4, 100] and k = 3
Output: [1000, 100, 10]
Example2
Input: [8, 7, 6, 5, 4, 3, 2, 1] and k = 5
Output: [8, 7, 6, 5, 4]
思路:用minHeap, NlogK.
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) {
// use minheap, O(NlogK);
if(nums == null || nums.length == 0 || k <= 0){
return new int[0];
}
PriorityQueue<Integer> pq = new PriorityQueue<Integer>();
for(int i = 0; i < nums.length; i++) {
if(pq.size() < k) {
pq.add(nums[i]);
} else {
if(nums[i] > pq.peek()){
pq.poll();
pq.add(nums[i]);
}
}
}
int[] res = new int[pq.size()];
int index = pq.size() - 1;
while(!pq.isEmpty()){
res[index--] = pq.poll();
}
return res;
}
}