题目:输入n个整数,找出其中最小的K个数。例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4,。
*知识点:Java PriorityQueue 调整新插入元素 转自 https://www.cnblogs.com/CarpenterLee/p/5488070.html
1 //siftUp() 2 private void siftUp(int k, E x) { 3 while (k > 0) { 4 int parent = (k - 1) >>> 1;//parentNo = (nodeNo-1)/2 5 Object e = queue[parent]; 6 if (comparator.compare(x, (E) e) >= 0)//调用比较器的比较方法 7 break; 8 queue[k] = e; 9 k = parent; 10 } 11 queue[k] = x; 12 }
*解法转自牛客网友 https://www.nowcoder.com/questionTerminal/6a296eb82cf844ca8539b57c23e6e9bf
做了少量修改,添加了部分注释便于理解
1 import java.util.ArrayList; 2 import java.util.PriorityQueue; 3 import java.util.Comparator; 4 public class Solution { 5 public ArrayList<Integer> GetLeastNumbers_Solution(int[] input, int k) { 6 ArrayList<Integer> result = new ArrayList<Integer>(); 7 int length = input.length; 8 //错误处理 9 if(k > length || k == 0){ 10 return result; 11 } 12 //Java的优先级队列是基于最小堆实现的 13 PriorityQueue<Integer> maxHeap = new PriorityQueue<Integer>(k, new Comparator<Integer>() { 14 //重写优先级队列里的compare方法,如果o2小于o1则堆会进行调整 15 @Override 16 public int compare(Integer o1, Integer o2) { 17 return o2.compareTo(o1); 18 } 19 }); 20 21 for (int i = 0; i < length; i++) { 22 //先让堆初始化,具有k个元素 23 if (maxHeap.size() != k) { 24 maxHeap.offer(input[i]); 25 } else if (maxHeap.peek() > input[i]) { 26 // Integer temp = maxHeap.poll(); 27 // temp = null; 28 maxHeap.poll(); 29 maxHeap.offer(input[i]); 30 } 31 } 32 for (Integer integer : maxHeap) { 33 result.add(integer); 34 } 35 return result; 36 } 37 }