最小的k个数(Java实现)


import java.util.PriorityQueue;

public class E40LeastKNumbers {
    //最小的K个数,利用大小为k的优先队列

    public static void findLeastNumbers(int[] numbers, int length, int k){
        if (numbers == null || length <= 0 || k == 0)
            return;
        //默认为最小优先队列,需要用Comparator改为最大优先队列
        PriorityQueue<Integer> priorityQueue = new PriorityQueue<>(Comparator.reverseOrder());
        for (int i = 0; i < length; i ++){
            if (priorityQueue.isEmpty() || priorityQueue.size() < k)
                priorityQueue.offer(numbers[i]);
            else if (priorityQueue.peek() > numbers[i]){
                priorityQueue.poll();
                priorityQueue.offer(numbers[i]);
        }
    }
        for (int number : priorityQueue)
            System.out.printf("%d\t", number);
            System.out.println();
}

    //测试用例
    public static void main(String[] args){
        int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9};
        E40LeastKNumbers.findLeastNumbers(numbers, 9, 1);
        E40LeastKNumbers.findLeastNumbers(numbers, 9, 0);
        E40LeastKNumbers.findLeastNumbers(numbers, 9, 9);
    }
}

你可能感兴趣的:(剑指offer)