输入n个整数,找出其中最小的K个数。例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4,。
显然可以考虑用快排的思想,这是比较常规的做法,就是选定一个temp,然后计数比这个temp小的数有多少,和k做比较,如果count小于k,继续利用快排的思想,递归,就是还要寻找k-count个,在比temp大的数里面。
本文尝试用堆排的思想,这也是可以的;
首先写出最小堆的的调整算法:
public static void adjustMinHeap(int[] a,int pos,int len){
int temp;
int child;
for(temp=a[pos];2*pos+1<=len;pos=child){
child=2*pos+1;
if(child<len && a[child]>a[child+1])
child++;
if(a[child]<temp)
a[pos]=a[child];
else
break;
}
a[pos]=temp;
}
就是找到子节点中较小的节点,然后跟父节点比较,使得父节点小于两个子节点。
再把堆排序:
for(int i=len/2-1;i>=0;i--)
adjustMinHeap(input,i,len-1);
最后就是输出了,每输出一个数,就和头节点交换,继续找出剩下堆的最小数,调整
for(int i=len-1;i>=len-k;i--){
int temp=input[0];
list.add(temp);
input[0]=input[i];
input[i]=temp;
adjustMinHeap(input,0,i-1);
}
最后的代码为:
import java.util.ArrayList;
public class Solution {
public static void adjustMinHeap(int[] a,int pos,int len){
int temp;
int child;
for(temp=a[pos];2*pos+1<=len;pos=child){
child=2*pos+1;
if(child<len && a[child]>a[child+1])
child++;
if(a[child]<temp)
a[pos]=a[child];
else
break;
}
a[pos]=temp;
}
public ArrayList<Integer> GetLeastNumbers_Solution(int [] input, int k) {
ArrayList<Integer> list=new ArrayList<Integer>();
if(input.length<k || k==0)
return list;
int len=input.length;
for(int i=len/2-1;i>=0;i--)
adjustMinHeap(input,i,len-1);
for(int i=len-1;i>=len-k;i--){
int temp=input[0];
list.add(temp);
input[0]=input[i];
input[i]=temp;
adjustMinHeap(input,0,i-1);
}
return list;
}
}
这样的时间复杂度是0(nlgn),写起来也没那么复杂。