package com.wsy.sword;
import java.util.ArrayList;
public class GetLeastNumbers
{
public static void main(String[] args)
{
GetLeastNumbers getLeastNumbers = new GetLeastNumbers();
int[] arr = {4,5,1,6,2,7,3,8};
ArrayList<Integer> list = getLeastNumbers.getLeastNumbers(arr, 4);
System.out.println(list.toString());
}
/*
* 输入n个整数,找出其中最小的K个数。例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4。
*
* 第一思路是构建小顶堆,调整k - 1次取到,最小的k个值
*
* 牛客推荐思路:使用优先队列实现,可参考
*/
public ArrayList<Integer> getLeastNumbers(int [] input, int k) {
ArrayList<Integer> list = new ArrayList<Integer>();
if(k < 1 || k > input.length){
return list;
}
//构建小顶堆
for(int i = input.length / 2 -1; i >= 0; i--){
adjustHeap(input, i, input.length);
}
//调整同时将堆顶元素加入list中
for(int j = input.length - 1; j > input.length - 1 - k; j--){
list.add(input[0]);
swap(input, 0, j);
adjustHeap(input, 0, j);
}
return list;
}
public void adjustHeap(int[] arr, int i, int len){
int temp = arr[i];
for(int k = 2*i + 1; k < len; k = 2*k +1){
if(k + 1 < len && arr[k] > arr[k + 1]){
k++;
}
if(arr[k] < temp){
arr[i] = arr[k];
i = k;
}else{
break;
}
}
arr[i] = temp;
}
public void swap(int[] arr, int i, int j){
arr[i] = arr[i]^arr[j];
arr[j] = arr[i]^arr[j];
arr[i] = arr[i]^arr[j];
}
}
/*
*构建k个数的大顶堆,遍历n - k个数与堆顶元素比较调整
*/
public static void main(String[] args){
int[] arr = {4,5,1,6,2,7,3,8};
System.out.println(getLeastNumbers(arr, 4));
}
public static ArrayList<Integer> getLeastNumbers(int [] input, int k){
ArrayList<Integer> list = new ArrayList<Integer>();
if(input == null || k > input.length)
return list;
//构建k个数的大顶堆
for (int i = k/2 - 1; i >= 0; i--){
adjust(input, 0, k);
}
for (int i = k; i < input.length; i++){
if(input[i] < input[0]){
swap(input, 0, i);
adjust(input, 0, k);
}
}
for (int i = 0; i < k; i++){
list.add(input[i]);
}
return list;
}
private static void adjust(int[] arr, int start, int end){
int temp = arr[start];
for(int k = 2*start + 1; k < end; k = 2*k + 1){
if(k + 1 < end && arr[k] < arr[k + 1])
k++;
if(temp < arr[k]){
arr[start] = arr[k];
start = k;
}else{
break;
}
}
arr[start] = temp;
}
private static void swap(int[] arr, int i, int j){
arr[i] = arr[i] ^ arr[j];
arr[j] = arr[i] ^ arr[j];
arr[i] = arr[i] ^ arr[j];
}
最小的K个数(JAVA)
最新推荐文章于 2022-07-12 19:26:10 发布