Given an integer array, find the top k largest numbers in it.
Example
Given [3,10,1000,-99,4,100]
and k = 3
.
Return [1000, 100, 10]
.
思路:由于需要按从大到小的顺序,因此直接用PriorityQueue即可,用Partition的方法的话还需要排序。直接用PriorityQueue 写的代码量少。
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) {
if (nums == null || nums.length < k) {
return null;
} int[] result = new int[k];
PriorityQueue<Integer> minHeap = new PriorityQueue<>();
for (int i = 0; i < nums.length; i++) {
if (minHeap.size() < k) {
minHeap.add(nums[i]);
} else {
int temp = minHeap.poll();
minHeap.add(Math.max(temp, nums[i]));
}
} for (int i = k - 1; i >= 0; i--) {
result[i] = minHeap.poll();
} return result;
}
};