题目描述
输入n个整数,找出其中最小的K个数。例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4,。
快速排序
import java.util.*;
public class Solution {
public ArrayList<Integer> GetLeastNumbers_Solution(int [] input, int k) {
ArrayList<Integer> al=new ArrayList<Integer>();
if(input.length < k || k <= 0||input.length ==0)
return al;
int low=0;
int high=input.length-1;
int index=partition(input,low,high);
while(index!=k-1){
if(index>k-1){
high=index-1;
index=partition(input,low,high);
}
else{
low=index+1;
index=partition(input,low,high);
}
}
for(int i=0;i<k;i++){
al.add(input[i]);
}
return al;
}
public static int partition(int[] data,int low,int high){
int temp=data[low];
while(low<high){
while(temp<=data[high]&&low<high){
high--;
}
data[low]=data[high];
while(temp>=data[low]&&low<high){
low++;
}
data[high]=data[low];
}
data[low]=temp;
return low;
}
}