求数组中最小的k个数
import java.util.*; public class Solution { public ArrayList<Integer> GetLeastNumbers_Solution(int[] input, int k) { ArrayList<Integer> result = new ArrayList<Integer>(); int length = input.length; if(k > length || k == 0){ return result; } //定义大顶堆 PriorityQueue<Integer> maxHeap = new PriorityQueue<Integer>(k, (o1,o2)->o2.compareTo(o1)); //该堆始终维护k个元素,出现比当前堆顶小的元素,那就干掉,重新调整堆 for (int i = 0; i < length; i++) { if (maxHeap.size() != k) { maxHeap.offer(input[i]); } else if (maxHeap.peek() > input[i]) { maxHeap.poll(); maxHeap.offer(input[i]); } } for (Integer integer : maxHeap) { result.add(integer); } return result; } }