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);
}
}
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个数
参考:堆排序原理