最小的K个数

来源:互联网 发布:2016淘宝女装销售排行 编辑:程序博客网 时间:2024/06/15 02:32
import java.util.ArrayList;
public class Solution {
    public ArrayList<Integer> GetLeastNumbers_Solution(int [] input, int k) {
         ArrayList<Integer> list = new ArrayList<Integer>();
if(input==null||input.length==0||k>input.length){
return list;
}
HeapSort(input,k);

for(int x=k;x<input.length;x++){
if(input[x]<input[0]){
input[0]=input[x];
AdjustHeap(input,0,k);
}
}
for(int x=0;x<k;x++){
list.add(input[x]);
}
return list;   
    }
    public void AdjustHeap(int a[],int i,int length){
   int child;
   int temp;
   for(;i*2+1<length;i=child){
       child = 2*i+1;
       temp=a[child];
       if(child<length-1&&a[child]<a[child+1]){
           child++;
       }
       if(a[i]<a[child]){
          temp=a[child];
          a[child]=a[i];
          a[i] = temp;
       }
       else break;
   }
}
public void HeapSort(int a[],int length){
   for(int i=length/2-1;i>=0;i--){
       AdjustHeap(a,i,length);
   }
}

}

题目来源:最小的k个数

参考:堆排序原理

0 0
原创粉丝点击