Problem
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].
Tags
Heap
Priority Queue
Solution
public class Solution {
public int[] topk(int[] nums, int k) {
//construct comparator, then priority-queue
Comparator<Integer> comparator = new Comparator<Integer>() {
public int compare(Integer v1, Integer v2) {
//can also use `return v2-v1;`
if (v1 < v2) {
return 1;
} else if (v1 > v2) {
return -1;
} else {
return 0;
}
}
};
PriorityQueue<Integer> maxHeap = new PriorityQueue<>(k, comparator);
//use maxHeap to get top k largest
for (int num: nums) {
maxHeap.offer(num);
}
//save to res array
int[] res = new int[k];
for (int i = 0; i < k; i++) {
res[i] = maxHeap.poll();
}
return res;
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。