输入n个整数,找出其中最小的K个数。例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4
import java.util.ArrayList;
import java.util.PriorityQueue;
public class T_29_LeastK {
public ArrayList<Integer> GetLeastNumbers_Solution(int[] input, int k) {
if (input == null || k <= 0 || k > input.length) {
return new ArrayList<>();
}
PriorityQueue<Integer> maxHeap = new PriorityQueue<>(k, (a, b) -> b.compareTo(a));
for (int e : input) {
if (maxHeap.size() < k) {
maxHeap.add(e);
} else if (maxHeap.peek() > e) {
maxHeap.poll();
maxHeap.add(e);
}
}
return new ArrayList<>(maxHeap);
}
}

- 最大优先队列,无论入队顺序,当前最大的元素优先出队。
- 用最大堆来实现最大优先队列,每一次入队操作就是堆的插入操作,每一次出队操作就是删除堆顶节点。
- 堆节点的上浮和下沉的时间复杂度为logN,所以优先队列入队和出队的时间复杂度也为logN
import java.util.PriorityQueue;
public class s {
public static void main(String[] args) {
PriorityQueue<Integer> maxHeap = new PriorityQueue<>((a, b) -> b.compareTo(a));
PriorityQueue<Integer> minHeap = new PriorityQueue<>((a, b) -> a.compareTo(b));
maxHeap.offer(3); minHeap.offer(3);
maxHeap.offer(2); minHeap.offer(2);
maxHeap.offer(5); minHeap.offer(5);
for (Integer s : maxHeap) {
System.out.print(s);
}
for (Integer s : minHeap) {
System.out.print(s);
}
}
}
- 大根堆:(a, b) -> b.compareTo(a)
- 小根堆:(a, b) -> a.compareTo(b)