题解 | #最小的K个数#
最小的K个数
https://www.nowcoder.com/practice/6a296eb82cf844ca8539b57c23e6e9bf
import java.util.*; public class Solution { public ArrayList<Integer> GetLeastNumbers_Solution(int [] input, int k) { PriorityQueue<Integer> heap=new PriorityQueue<Integer>((o1,o2) -> {return o2-o1;}); ArrayList<Integer> list = new ArrayList<Integer>(); if(input.length==0||k==0){ return list; } for(int i=0;i<k;i++){ heap.add(input[i]); } int top1=heap.peek(); for(int i=k;i<input.length;i++){ int top=heap.peek(); if(top>input[i]){ heap.poll(); heap.add(input[i]); } } for(int i=0;i<k;i++){ list.add(heap.poll()); } return list; } }