//法一:基于快排partition函数,时间复杂度为O(n)
public class SmallerKnumber {
public static void main(String[] args) {
int[]a={2,4,5,46,32,42,7};
int k=5;
int start=0,end=a.length-1;
int index=partition(a,start,end);
while(index!=k-1){
if(index>k-1){
end=index-1;
index=partition(a,start,end);
}else{
start=index+1;
index=partition(a,start,end);
}
}
for(int i=0;i<k;i++){
System.out.print(a[i]+" ");
}
}
public static int partition(int[]a,int start,int end){
int i=start,j=end;
int x=a[start];
while(i<j){
while(i<j&&a[j]>=x)j--;
a[i]=a[j];
while(i<j&&a[i]<=x)i++;
a[j]=a[i];
}
a[i]=x;
return i;
}
}
//法二:
package 数组;
import java.util.ArrayList;
import java.util.PriorityQueue;
import java.util.Comparator;
public class SmallerKnumber {
public static void main(String[] args) {
int[]a={2,4,5,46,32,42,7};
int k=5;
ArrayList<Integer> array=GetLeastNumbers_Solution(a,k);
for(int i=0;i<array.size();i++){//遍历ArrayList数组
System.out.print(array.get(i)+" ");
}
}
public static ArrayList<Integer> GetLeastNumbers_Solution(int[] input, int k) {
ArrayList<Integer> result = new ArrayList<Integer>();//返回的数组
int length = input.length;
if(k > length || k == 0){
return result;
}
PriorityQueue<Integer> maxHeap = new //PriorityQueue为大根堆
PriorityQueue<Integer>(k, new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {//排序规则
return o2.compareTo(o1);
}
});
for (int i=0;i<length;i++) {
if (maxHeap.size()<k) {
maxHeap.offer(input[i]);
} else if (maxHeap.peek() > input[i]) {
Integer temp = maxHeap.poll();
temp = null;
maxHeap.offer(input[i]);
}else{}
}
for (Integer integer : maxHeap) {
result.add(integer);
}
return result;
}
}