思路一:先将数组排序完序后取k个数就完事了,基于复杂度的考虑,先使用堆排序,复杂度为O(n*logn)
思路二:可实现维持一个k个数的大根堆,经过维持过的大根堆,就有了较小的k个数,取出即可。
具体步骤:1.可先从数组中取k个数实现一个大根堆,
2.遍历原数组,将大根堆堆顶元素和原数组中剩余的数进行比较,
如果此数组中的数小于堆顶元素,将数组的数赋值给大根堆的堆顶元素,再调整堆的顺序,使其恢复为大根堆
如果此数组中的数大于堆顶元素,什么也不做。
分析:时间复杂度为O(n*logk)
public static ArrayList<Integer> GetLeastNumbers_Solution(int[] input, int k) {
ArrayList<Integer> list=new ArrayList<>();
int help[] = new int[k];
// 形成大根堆
for (int i = 0; i < k; i++) {//数组中形成0-k的大根堆
heapInsert(help, input[i], i);
}
//将大根堆中的数和数组剩余的数进行比较,调整,维持大根堆,
for(int j=k;j!=input.length;j++) {
if(input[j]<help[0]) {
help[0]=input[j];
heapify(help,0,k);
}
}
for(int i=0;i<help.length;i++) {
list.add(help[i]);
}
return list;
}
// 形成大根堆
// 传入一个数组,和一个值(这个值来于其他的数组),一个索引,
public static void heapInsert(int help[], int value, int index) {
help[index] = value;// 将另外一个数组的值赋值给要形成大根堆的数组。
while (index != 0) {
int parent = (index - 1) / 2;
if (help[parent] < help[index]) {
swap(help, parent, index);
index = parent;
} else {
break;
}
}
}
// 调整大根堆
public static void heapify(int[] arr, int index, int heapSize) {
int left = 2 * index + 1;
while (left < heapSize) {
int largest = left + 1 < heapSize && arr[left + 1] > arr[left] ? left + 1 : left;
largest = arr[index] > arr[largest] ? index : largest;
if (largest == index) {
break;
}
swap(arr, index, largest);
index = largest;
left = 2 * index + 1;
}
}
public static void swap(int arr[], int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
public static void main(String[] args) {
int arr[] = {4,5,1,6,2,7,3,8};
ArrayList<Integer> getLeastNumbers_Solution = GetLeastNumbers_Solution(arr,4);
for (Integer integer : getLeastNumbers_Solution) {
System.out.print(integer+"");
}
}