/*
输入n个整数,找出其中最小的K个数。例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4,。
*/
//本题借助函数sort可以很方便的解决,但是建议大家不要这样做。可以使用堆来实现。
import java.util.*;
public class Class34 {
public ArrayList<Integer> GetLeastNumbers_Solution(int [] input, int k) {
ArrayList<Integer> list = new ArrayList<Integer>();
if(input == null || k <= 0 || k > input.length){
return list;
}
int[] heapArray = Arrays.copyOfRange(input, 0, k);
buildHeap(heapArray);
for(int i = k; i < input.length; i++){
if(input[i] < heapArray[0]){
heapArray[0] = input[i];
maxHeap(heapArray,0);
}
}
for(int i = heapArray.length - 1; i >= 0; i--){
list.add(heapArray[i]);
}return list;
}
public void buildHeap(int[] array){
for(int i = array.length/2 - 1; i >= 0; i--){
maxHeap(array,i);
}
}
public void maxHeap(int[] array, int i){
int left = 2 * i + 1;
int right = left + 1;
int maxHeapIndex = 0;
if(left < array.length && array[left] > array[i]){
maxHeapIndex = left;
}else{
maxHeapIndex = i;
}
if(right < array.length && array[right] > array[i]){
maxHeapIndex = right;
}
if(maxHeapIndex != i){
int temp = array[i];
array[i] = array[maxHeapIndex];
array[maxHeapIndex] = temp;
maxHeap(array,maxHeapIndex);
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}