快速查找代码来源:https://leetcode-cn.com/problems/zui-xiao-de-kge-shu-lcof/solution/3chong-jie-fa-miao-sha-topkkuai-pai-dui-er-cha-sou/
public int[] getLeastNumbers(int[] arr, int k) {
Arrays.sort(arr);
return Arrays.copyOfRange(arr, 0, k);
}
@Test
public void test13(){
int[] arr = {3,2,1};
System.out.println(Arrays.toString(getLeastNumbers(arr, 2)));
}
//寻找第K大的问题:
public int[] getLeastNumbers1(int[] arr,int k) {
if (k == 0 || arr.length == 0){
return new int[0];
}
//最后一个参数表示的是我们要找的是下标是k - 1的数;
return quickSearch(arr,0,arr.length - 1,k - 1);
}
private int[] quickSearch(int[] arr, int low, int high, int k) {
//每快排切分一次,就返回一个切分好的值j,j代表左侧的值小于arr[j],右侧的值大于arr[j]
int j = partition(arr,low,high);
//如果返回的值刚好就是k,那就直接返回左侧的值就可以了
if (j == k){
return Arrays.copyOf(arr,k + 1);
}
//根据小标j与k的大小关系,决定继续切分左段还是右端
return j > k ? quickSearch(arr,low,j - 1,k) : quickSearch(arr,j + 1,high,k);
}
private int partition(int[] arr, int low, int high) {
//基准值,找第一个low下标的值
int v = arr[low];
//从low开始比
int i = low;
int j = high + 1;
while (true){
while (++i <= high && arr[i] < v);
while (--j >= low && arr[j] > v);
if (i >= j){
break;
}
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
arr[low] = arr[j];
arr[j] = v;
return j;
}