题目
输入n个整数,找出其中最小的K个数。例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4,。
解题思路
用快速选择找出第k大的数,前面的就是最小的k个数。
代码如下
import java.util.*;
public class Solution {
public ArrayList<Integer> GetLeastNumbers_Solution(int[] input, int k) {
if (input.length == 0) return new ArrayList<>();
if (k > input.length) return new ArrayList<>();
return GetLeastNumbers_Solution(input, 0, input.length,k-1);
}
public ArrayList<Integer> GetLeastNumbers_Solution(int[] input, int l, int r, int k){
int index = partition(input, l, r);
if (index == k) {
ArrayList<Integer> list = new ArrayList<>();
for (int i = 0; i <= k; i++) {
list.add(input[i]);
}
return list;
} else if (index < k) {
return GetLeastNumbers_Solution(input, index+1,r,k);
} else {
return GetLeastNumbers_Solution(input, l, index, k);
}
}
public int partition(int[] input, int l, int r) {
int x = input[l];
int lo = l + 1, hi = r-1;
while (true) {
while (lo <= hi && input[lo] < x) {
lo++;
}
while (lo <= hi && input[hi] > x) {
hi--;
}
if (lo >= hi) {
break;
}
swap(input, lo, hi);
}
swap(input, l, lo-1);
return hi;
}
public void swap(int[] arr, int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}