输入n个整数,找出其中最小的K个数。例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4,。
import java.util.ArrayList;
import java.util.Arrays;
public class Solution {
private ArrayList<Integer> ret = new ArrayList<>();
public ArrayList<Integer> GetLeastNumbers_Solution(int [] input, int k) {
if(input.length == 0 || k == 0) return ret;
GetLeastNumbers_Solution(input, 0, input.length-1, k);
return ret;
}
private void GetLeastNumbers_Solution(int array[], int start, int end, int k){
if(start <= end){
int minPtr = partition(array, start, end);
if(minPtr == k-1){
Arrays.sort(array, 0, minPtr);
for(int i = 0; i < k; i++) ret.add(array[i]);
} else if(minPtr < k-1){
GetLeastNumbers_Solution(array, minPtr+1, end, k);
} else {
GetLeastNumbers_Solution(array, start, minPtr-1, k);
}
}
}
private int partition(int[] array, int start, int end){
int target = array[end];
int minPtr = start-1;
for(int i = start; i < end; i++){
if(array[i] < target){
minPtr++;
swap(array, minPtr, i);
}
}
swap(array, ++minPtr, end);
return minPtr;
}
private void swap(int[] array, int i1, int i2){
int temp = array[i1];
array[i1] = array[i2];
array[i2] = temp;
}
}