题目:输入n个整数,找出其中最小的K个数。例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4,。
思路:运用快排的思想,每次排序后,point点左边的数都小于point,因此只要让point的坐标等于k-1时,point以及它左边的数就是最小的k个数。但是这样会改变数组原有次序。
另一种思路是事先设置一个大小为k的容器,同时设置一个变量max用来记录当前容器中最大的数,如果容器没有满,那么就将数字插入,如果满了,拿出最大的数,然后插入新的数字,直到遍历完整个数组。这样不会改变数组原有次序。
代码:
ArrayList<Integer> GetLeastNumbers_Solution(int [] input, int k) {
ArrayList<Integer> result = new ArrayList<Integer>();
int num = input.length;
if (num < k) {
return result;
}
int index = Partition(input, 0, input.length - 1);
while (index != k - 1) {
if (index > k - 1) {
index = Partition(input, 0, index - 1);
} else {
index = Partition(input, index + 1, input.length - 1);
}
}
for (int i = 0 ; i < k ; i++) {
result.add(input[i]);
}
return result;
}
int Partition(int[] nums, int left, int right) {
int point = nums[left];
while (left < right) {
while (left < right && nums[right] >= point) {
right--;
}
if (left < right) {
nums[left] = nums[right];
}
while (left < right && nums[left] <= point) {
left++;
}
if (left < right) {
nums[right] = nums[left];
}
}
nums[left] = point;
return left;
}
// 第二种方法
public static ArrayList<Integer> GetLeastNumbers_Solution2(int[] input, int k) {
ArrayList<Integer> result = new ArrayList<Integer>(k); // 大小为k的容器
int num = input.length;
if (num < k || k <= 0) {
return result;
}
int maxIndex = 0;
result.add(input[0]);
for (int i = 1; i < input.length; i++) {
if (result.size() == k) {
if (result.get(maxIndex) > input[i]) {
result.set(maxIndex, input[i]);
// 重新寻找最大值所在的位置
for (int j = 0; j < result.size(); j++) {
if (result.get(j) > result.get(maxIndex)) {
maxIndex = j;
}
}
}
} else {
result.add(input[i]);
if (input[i] > result.get(maxIndex)) {
maxIndex = i;
}
}
}
return result;
}