题解 | #最小的K个数# -- 优先队列
最小的K个数
http://www.nowcoder.com/practice/6a296eb82cf844ca8539b57c23e6e9bf
import java.util.ArrayList;
import java.util.Comparator;
import java.util.PriorityQueue;
public class Solution {
public ArrayList<Integer> GetLeastNumbers_Solution(int [] input, int k) {
if (k == 0) {
return new ArrayList<>();
}
PriorityQueue<Integer> maxHeap = new PriorityQueue<Integer>
(k, new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o2.compareTo(o1);
}
});
for (Integer i : input) {
if (maxHeap.size() < k) {
maxHeap.add(i);
} else {
if (maxHeap.peek() > i) {
maxHeap.remove();
maxHeap.add(i);
}
}
}
ArrayList<Integer> result = new ArrayList<>();
while(maxHeap.size() > 0) {
result.add(maxHeap.remove());
}
return result;
}
}