题目描述
输入n个整数,找出其中最小的K个数。例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4,。
思路
这一题很简单,可以先用循环将整数排序,然后在输出前k个数,但是这样的话时间复杂度比较高,若是使用Arrays.sort来排序的话,内部好像是使用的快速排序和优化的合并排序合并排序的时间复杂度是nlogn, 快速排序的平均时间复杂度也是nlogn,但是合并排序的需要额外的n个引用的空间:
import java.util.Arrays;
public class Solution {
public ArrayList<Integer> GetLeastNumbers_Solution(int [] input, int k) {
Arrays.sort(input);
ArrayList<Integer> nums = new ArrayList<Integer>();
for(int i=0;i<k;i++)
nums.add(input[i]);
return nums;
}
}
下面是一个冒泡排序的思想,最外层只循环了K次,也就是说每次循环筛选出一个最小值放在数组最后面,当然这个时间复杂度是O(N*K),也不是最优:
public ArrayList<Integer> GetLeastNumbers_Solution(int [] input, int k) {
ArrayList<Integer> al = new ArrayList<Integer>();
if (k > input.length) {
return al;
}
for (int i = 0; i < k; i++) {
for (int j = 0; j < input.length - i - 1; j++) {
if (input[j] < input[j + 1]) {
int temp = input[j];
input[j] = input[j + 1];
input[j + 1] = temp;
}
}
al.add(input[input.length - i - 1]);
}
return al;
}
最优的是使用PriorityQueue当作Heap,用最大堆保存这k个数,每次只和堆顶比,如果比堆顶小,删除堆顶,新数入堆,时间复杂度是O(nlogk) :
import java.util.ArrayList;
import java.util.PriorityQueue;
import java.util.Comparator;
public class Solution {
public ArrayList<Integer> GetLeastNumbers_Solution(int[] input, int k) {
ArrayList<Integer> result = new ArrayList<Integer>();
int length = input.length;
if(k > length || k == 0){
return result;
}
PriorityQueue<Integer> maxHeap = new PriorityQueue<Integer>(k, new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o2.compareTo(o1);
}
});
for (int i = 0; i < length; i++) {
if (maxHeap.size() != k) {
maxHeap.offer(input[i]);
} else if (maxHeap.peek() > input[i]) {
Integer temp = maxHeap.poll();
temp = null;
maxHeap.offer(input[i]);
}
}
for (Integer integer : maxHeap) {
result.add(integer);
}
return result;
}
}
这里PriorityQueue结构可以参考这篇博文https://www.cnblogs.com/CarpenterLee/p/5488070.html