方法一:优先队列
public int[] getLeastNumbers(int[] arr, int k) {
PriorityQueue<Integer> maxHeap=new PriorityQueue<>(new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o2-o1;
}
});
for(int i=0;i<arr.length;i++){
if(maxHeap.size()<k){
maxHeap.add(arr[i]);
}
else{
if(arr[i]<maxHeap.peek()){
maxHeap.poll();
maxHeap.add(arr[i]);
}
}
}
int[] res=new int[k];
for(int i=0;i<k;i++){
res[i]=maxHeap.poll();
}
return res;
}
方法二:快排
public int[] getLeastNumbers(int[] arr, int k){
quickSort(arr,0,arr.length-1);
return Arrays.copyOf(arr,k);
}
public void quickSort(int[] arr,int left,int right){
if(left>=right) return;
int low=left;
int high=right;
while(low<high){
while(low<high&&arr[high]>=arr[left]) high--;
while(low<high&&arr[low]<=arr[left]) low++;
swap(arr,low,high);
}
swap(arr,low,left);
quickSort(arr,left,low-1);
quickSort(arr,low+1,right);
}
public void swap(int[] arr,int i,int j){
int temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}