import java.util.Arrays;
public class Algorithm {
public static void main(String[] args) {
int[] arr = {1,3,5,7,2,4,6,8};
System.out.println(Arrays.toString(new Solution().smallestK(arr, 4)));
}
}
class Solution {
public int[] smallestK(int[] arr, int k) {
/**
* 如果数组为空或者返回个数为空,就返回空数组
*/
if (k == 0 || arr == null | arr.length == 0){
int[] res = new int[0];
return res;
}
int temp = 0;
int[] res = new int[k];
/**
* 返回arr[0, k - 1]
*/
int target = k - 1;
sort(arr, 0, arr.length - 1, target, temp);
for (int i = 0; i < k; i++) {
res[i] = arr[i];
}
return res;
}
public static void sort(int[] arr, int left, int right, int target, int temp){
int p = partition(arr, left, right, temp);
/**
* 使用双路排序法,如果返回的索引刚好是目标,就直接return
* 否则只用判断一个区间
*/
if (p == target){
return;
}
else if (target < p) {
sort(arr, left, p - 1, target, temp);
}
else {
sort(arr, p + 1, right, target, temp);
}
}
public static<E extends Comparable<E>> int partition(int[] arr, int left, int right, int temp) {
int i = left + 1;
int j = right;
while (i <= j){
if (arr[i] < arr[left]){
i++;
}
else if (arr[j] > arr[left]){
j--;
}
else {
swap(arr, i, j);
i++;
j--;
}
}
swap(arr, j, left);
return j;
}
public static void swap(int[] arr, int i, int j) {
int temp;
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
https://leetcode-cn.com/problems/smallest-k-lcci/