题目描述
输入n个整数,找出其中最小的K个数。例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4,。
牛客传送门:点击打开链接
思路一:不断地利用快排partition函数,当index == k-1时结束。(注意这里是k-1,因为index表示数组位置)
思路二:利用优先队列。
代码一:
public class Title30 {
public ArrayList<Integer> GetLeastNumbers_Solution(int [] input, int k) {
ArrayList<Integer> result = new ArrayList<Integer>(k);
if(input == null || input.length == 0 || k<=0 || k > input.length)
return result;
int index = -1,begin = 0,end = input.length - 1;
k--;
while(index != k){
index = partition(input,begin,end);
if(index > k)
end = index - 1;
else if(index < k)
begin = index + 1;
}
quickSort(input,0,k);
for(int i=0;i<=k;i++){
result.add(input[i]);
}
return result;
}
public void quickSort(int[] array,int begin,int end){
if(begin < end){
int index = partition(array,begin,end);
quickSort(array,begin,index-1);
quickSort(array,index+1,end);
}
}
public int partition(int[] array,int begin,int end){
int small = begin-1;
for(int i=begin;i<end;i++){
if(array[i] < array[end]){
++small;
if(i != small)
swap(array,i,small);
}
}
++small;
swap(array,small,end);
return small;
}
public void swap(int[] array,int posA,int posB){
if(posA == posB)
return ;
array[posA] = array[posA] + array[posB];
array[posB] = array[posA] - array[posB];
array[posA] = array[posA] - array[posB];
}
public static void main(String[] args) {
int[] a = {4,5,1,6,2,7,3,8};
System.out.println(new Title30().GetLeastNumbers_Solution(a, 8));
System.out.println(new Title30().GetLeastNumbers_Solution(a, 4));
}
}
public class Title30 {
public ArrayList<Integer> GetLeastNumbers_Solution(int [] input, int k) {
ArrayList<Integer> result = new ArrayList<Integer>(k);
if(input == null || input.length == 0 || k<=0 || k > input.length)
return result;
// 优先队列
PriorityQueue<Integer> priQueue = new PriorityQueue<Integer>(k, new Comparator<Integer>(){
public int compare(Integer o1, Integer o2) {
return o2 - o1;
}});
for(int num : input){
// 如果队列满了,则将这个数与队列的最大值比较。
if(priQueue.size() == k){
if(num < priQueue.peek()){
priQueue.poll();
priQueue.add(num);
}
}else{
priQueue.add(num);
}
}
result.addAll(priQueue);
Collections.sort(result);
return result;
}
public static void main(String[] args) {
int[] a = {4,5,1,6,2,7,3,8};
System.out.println(new Title30().GetLeastNumbers_Solution(a, 8));
System.out.println(new Title30().GetLeastNumbers_Solution(a, 4));
}
}