1. 程式人生 > >【劍指offer】求一組資料中最小的K個數

【劍指offer】求一組資料中最小的K個數

題目:輸入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 }