1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| public class Solution { public ArrayList<Integer> GetLeastNumbers_Solution(int [] input, int k) { ArrayList<Integer> result = new ArrayList<>(); int length = input.length; if(k > length || k == 0){ return result; } PriorityQueue<Integer> maxHeap = new PriorityQueue<>(k,new Comparator<Integer>() { @Override public int compare(Integer o1, Integer o2) { return o2.compareTo(o1); } }); for (int i = 0; i < input.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; } }
|