# 剑指 Offer 40. 最小的k个数

## 题目描述

0 <= k <= arr.length <= 10000
0 <= arr[i] <= 10000

class Solution {

public int[] getLeastNumbers(int[] arr, int k) {
if(k == 0 || k > arr.length) return new int[0];
int l = 0, r = arr.length - 1;
while(l < r){
int j = quickSort(arr, l, r);
if(j == k) break;
if(j > k) r = j - 1;
else l = j + 1;
}
return  Arrays.copyOf(arr, k);
}
public int quickSort(int[] arr, int l, int r){
int i = l, j = r + 1, x = arr[l];
while(i < j){
while(++i <= r && arr[i] < x);
while(--j >= l && arr[j] > x);
if(i < j){
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}else break;
}
arr[l] = arr[j];
arr[j] = x;
return j;
}
}


class Solution {
public int[] getLeastNumbers(int[] arr, int k) {
int[] ans = new int[k];
if(k == 0) return ans;
PriorityQueue<Integer> q = new PriorityQueue<Integer>(new Comparator<Integer>(){
public int compare(Integer a, Integer b){
return a - b;  //小根堆
}
});
for(int i = 0; i < arr.length; i++)
q.offer(arr[i]);
for(int i = 0; i < k; i++)
ans[i] = q.poll();
return ans;
}
}


06-09 119

03-20 193
05-13 6224
11-05 43
03-06 171
04-26 82
©️2020 CSDN 皮肤主题: 数字20 设计师:CSDN官方博客