前言:
今天最后一道题,实现很简单。但是想要降低时间复杂度,应该选用什么样的方法。
题目描述
输入n个整数,找出其中最小的K个数。例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4,。
解题思路
这道题,我首先想到的方法就是排序,排好序后接着从头开始遍历K个数即可。这里排序算法可以使用快排、归并、冒泡、选择排序等。都可以使用。但是这几个算法复杂度都很高。所以在这里推荐一个最大堆的实现方法。
我们可以使用最大堆来实现。我们用最大堆保存这k个数,每次只和堆顶比,如果比堆顶小,删除堆顶,新数入堆。这样时间复杂度为O(nlogk)。因为堆中总共k个数,每插入或删除一个数,都要调整一次堆,即时间复杂度为O(logk), 共循环n次,插入的次数最坏情况为n次,删除为n-k次,而平均下来插入次数也不少,所以大致估计时间复杂度就在nlogk。
代码样例
Arrays.sort排序 可以AC
package com.asong.leetcode.GetLeastNumbers_Solution;
import java.util.ArrayList;
import java.util.Arrays;
/**
* 最小的k个数
* 输入n个整数,找出其中最小的K个数。例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4,。
*/
public class Solution {
public ArrayList<Integer> GetLeastNumbers_Solution(int [] input, int k) {
ArrayList<Integer> res = new ArrayList<Integer>();
if(input==null||input.length==0||k<0||k>input.length)
{
return res;
}
Arrays.sort(input);
for (int i = 0; i < k; i++) {
res.add(input[i]);
}
return res;
}
}
最大堆实现
package com.asong.leetcode.GetLeastNumbers_Solution;
import java.util.PriorityQueue;
import java.util.ArrayList;
import java.util.Comparator;
/**
* 最小的k个数 大顶堆实现 比这个树大抛弃,小则 替换。
*/
public class Solution1 {
public ArrayList<Integer> GetLeastNumbers_Solution(int [] input, int k) {
ArrayList<Integer> result = new ArrayList<Integer>();
if(input == null || input.length == 0 || k==0 || k>input.length)
{
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 < input.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 i:maxHeap
) {
result.add(i);
}
return result;
}
}