本文首發于我的個人部落格: 尾尾部落
題目描述
輸入n個整數,找出其中最小的K個數。例如輸入4,5,1,6,2,7,3,8這8個數字,則最小的4個數字是1,2,3,4。
解題思路
兩種方法:
- 法1:先對數組排序,然後取出前k個
- 法2:利用最大堆儲存這k個數,每次隻和堆頂比,如果比堆頂小,删除堆頂,新數入堆。
參考代碼
法1:
import java.util.ArrayList;
import java.util.Arrays;
public class Solution {
public ArrayList<Integer> GetLeastNumbers_Solution(int [] input, int k) {
ArrayList<Integer> res = new ArrayList<Integer>();
if(input == null || k ==0 || k > input.length)
return res;
Arrays.sort(input);
for(int i=0; i<k; i++)
res.add(input[i]);
return res;
}
}
法2:
import java.util.ArrayList;
import java.util.PriorityQueue;
import java.util.Comparator;
public class Solution {
public ArrayList<Integer> GetLeastNumbers_Solution(int [] input, int k) {
ArrayList<Integer> res = new ArrayList<Integer>();
if(input == null || k ==0 || k > input.length)
return res;
PriorityQueue<Integer> maxHeap = new PriorityQueue<Integer>(k, new Comparator<Integer>() {
public int compare(Integer e1, Integer e2) {
return e2 - e1;
}
});
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 i: maxHeap){
res.add(i);
}
return res;
}
}