package com.niuke;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.PriorityQueue;
/**
* Created by admin on 2018/3/10.
* 输入n个整数,找出其中最小的K个数。
* 例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4,。
优先队列原理实现
*/
public class MinNumber {
//用最大堆保存这k个数,每次只和堆顶比,如果比堆顶小,删除堆顶,新数入堆。
public ArrayList<Integer> GetLeastNumbers_Solution(int [] input, int k) {
ArrayList<Integer> list=new ArrayList<>();
int len=input.length;
if(k>len||k==0) {
return list;
}
//优先队列的实现原理:
[这里写链接内容](http://blog.csdn.net/u013309870/article/details/71189189)
PriorityQueue<Integer> maxheap=new PriorityQueue<Integer>(k, new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o2.compareTo(o1);
}
//优先队列默认为小顶堆 用一个Comparator将其转化为一个大顶堆
});
for(int i=0;i<len;i++) {
if(maxheap.size()!=k) {//如果队列中的数比要求的数少,则继续向优先队列中添加
maxheap.offer(input[i]);
} else if(maxheap.peek()>input[i]){//如果队列中的数等于要求的数、且队头的数大于新来的数
Integer tmp=maxheap.poll();//弹出队头的数。并插入新来的数
tmp=null;
maxheap.offer(input[i]);
}
}
for(Integer integer:maxheap) {
list.add(integer);
}
return list;
}
@Test
public void test() {
int []a={2,4,6,7,1,3,8};
ArrayList list=GetLeastNumbers_Solution(a,3);
for(int i=0;i<list.size();i++) {
System.out.println(list.get(i));
}
}
}
最小的K个数
最新推荐文章于 2020-07-01 18:20:18 发布