题解 | #最小的K个数#
最小的K个数
https://www.nowcoder.com/practice/6a296eb82cf844ca8539b57c23e6e9bf
import java.util.*; public class Solution { public ArrayList<Integer> GetLeastNumbers_Solution(int [] input, int k) { ArrayList<Integer> res = new ArrayList<>(); if (input == null || k < 1 || input.length < k) { return res; } PriorityQueue<Integer> pq = new PriorityQueue<>((a, b) -> b - a); for (int i = 0; i < k; i++) { pq.offer(input[i]); } for (int i = k; i < input.length; i++) { if (input[i] < pq.peek()) { pq.poll(); pq.offer(input[i]); } } while (!pq.isEmpty()) { res.add(pq.poll()); } Collections.reverse(res); return res; } }