找到數組中最小的k個數



/*輸入整數數組 arr ,找出其中最小的 k 個數。例如,輸入4、5、1、6、2、7、3、8這8個數字,
則最小的4個數字是1、2、3、4。
示例 1:
輸入:arr = [3,2,1], k = 2
輸出:[1,2] 或者 [2,1]
示例 2:
輸入:arr = [0,1,2,1], k = 1
輸出:[0]
https://leetcode-cn.com/problems/zui-xiao-de-kge-shu-lcof/*/
//最小的k個數
public static int[] getLeastNumbers(int[] arr, int k) {
/* PriorityQueue<Integer> pQueue = new PriorityQueue<Integer>(arr.length, new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o1 - o2;
}
});*/
PriorityQueue<Integer> pQueue = new PriorityQueue<Integer>();//默認小頂堆
for (int i:arr
) {
pQueue.add(i);
}
int[] result = new int[k];
for (int i = 0; i < k; i++) {
result[i] = pQueue.poll();
}
return result;
}
//最小的k個數
public static int[] getLeastNumbers2(int[] arr, int k) {
//大頂堆
PriorityQueue<Integer> pQueue = new PriorityQueue<Integer>(new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o2-o1;
}
});//默認小的在上
for (int i:arr
) {
if(pQueue.size() < k ){
pQueue.add(i);
}else if(!pQueue.isEmpty()&&i<pQueue.peek()){
pQueue.poll();
pQueue.add(i);
}
}
int[] result = new int[k];
for (int i = 0;i<k ;i++) {
result[i] = pQueue.poll();
}
return result;
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM