题目描述
输入n个整数,找出其中最小的K个数。例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4,。
解法一:使用Parttition函数
解法二:使用最大堆,一、在k个整数中找到最大数,二、有可能在这个容器中删除最大数,三、有可能插入一个新数
Java使用PriorityQueue优先队列来建堆
解法一
private int Partition(int[] input, int begin, int end) {
int pivot=input[begin];
while(begin<end){
while(input[end]>=pivot &&begin<end)end--;
input[begin]=input[end];
while(input[begin]<=pivot&&begin<end)begin++;
input[end]=input[begin];
}
input[begin]=pivot;
return begin;
}
public ArrayList<Integer> GetLeastNumbers_Solution(int[] input, int k) {
ArrayList<Integer>arrayList=new ArrayList<>();
if(k<=0 ||input.length==0||k>input.length)return arrayList;
int begin=0;
int end=input.length-1;
int index=Partition(input, begin, end);
while(index!=k-1){
if(index>k-1){
end=index-1;
index =Partition(input, begin, end);
}
else{
begin=index+1;
index=Partition(input, begin, end);
}
}
for(int i=0;i<k;i++){
arrayList.add((Integer)input[i]);
}
return arrayList;
解法二:
public ArrayList<Integer> GetLeastNumbers_Solution(int[] input, int k) {
ArrayList<Integer>result=new ArrayList<Integer>();
int length=input.length;
if(k==0 ||k>length)return result;
//最大堆
PriorityQueue<Integer>maxHeap=new PriorityQueue<Integer>(k,new Comparator<Integer>() {
@Override
public int compare(Integer o1,Integer o2){
return o2.compareTo(o1);
}
});
for(int i=0;i<length;i++){
if(maxHeap.size()!=k){
maxHeap.offer(input[i]);
}else if(maxHeap.peek()>input[i]){
Integer tmp=maxHeap.poll();
tmp=null;
maxHeap.offer(input[i]);
}
}
for(Integer integer:maxHeap){
result.add(integer);
}
return result;
}