解法一:构造最大堆(堆顶元素是堆中元素最大值)
import java.util.*;
class Solution {
public int[] getLeastNumbers(int[] arr, int k) {
if(arr == null || arr.length < k || k == 0)
return new int[0];
PriorityQueue<Integer> maxHeap = new PriorityQueue<>((o1, o2) -> o2 - o1);
for(int num : arr){
if(maxHeap.size() < k)
maxHeap.add(num);
else
if(maxHeap.peek() > num){
maxHeap.poll();
maxHeap.add(num);
}
}
int[] res = new int[k];
for(int i = 0; i < k; ++ i)
res[i] = maxHeap.poll();
return res;
}
}
解法二:快排(推荐)
class Solution {
public int[] getLeastNumbers(int[] arr, int k) {
if(arr == null || arr.length == 0 || arr.length < k )
return new int[0];
quickSort(arr, 0, arr.length - 1, k);
return Arrays.copyOf(arr, k);
}
private void quickSort(int[] arr, int leftBound, int rightBound, int k){
if(leftBound > rightBound)
return;
int middle = patition(arr, leftBound, rightBound);
if(middle == k - 1)
return;
else if(middle > k - 1)
quickSort(arr, leftBound, middle - 1, k);
else
quickSort(arr, middle + 1, rightBound, k);
}
private int patition(int[] arr, int leftBound, int rightBound){
int pivot = arr[rightBound];
int left = leftBound, right = rightBound - 1;
while(left <= right){
while(left <= right && arr[left] <= pivot)
left++;
while(left <= right && arr[right] > pivot)
right--;
if(left < right)
swap(arr, left, right);
}
swap(arr, left, rightBound);
return left;
}
private void swap(int[] arr, int i, int j){
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}