题目:输入n个整数,找出其中最小的k个数。例如,输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数是1,2,3,4.
package jianzhi_offer;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.PriorityQueue;
public class P40_Solution {
/*
* 建立容量为k的大顶堆,若堆的容量小于k则加入堆中,若大于等于k且要加入的数比堆顶小则删除堆顶元素,加入
*/
public ArrayList<Integer> GetLeastNumbers_Solution(int[] input, int k) {
ArrayList<Integer> list = new ArrayList<>();
if (input == null || input.length == 0 || input.length < k || k < 0)
return list;
PriorityQueue<Integer> maxHeap = new PriorityQueue<>(k, new Comparator<Integer>() {
@Override
public int compare(Integer arg0, Integer arg1) {
return arg1.compareTo(arg0);
}
});
int len = input.length;
for (int i = 0; i < len; i++) {
if (maxHeap.size() < k) {
maxHeap.offer(input[i]);
} else if (maxHeap.peek() > input[i]) {
int temp = maxHeap.poll();
maxHeap.offer(input[i]);
}
}
for (Integer item : maxHeap) {
list.add(item);
}
return list;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}