题目001 使用PriorityQueue 获取最大/最小N个数

public class PriorityQueueTest {
    private static PriorityQueue<Integer> maxHeap, minHeap;

    public static void main(String[] args) {
        int[] arr = {7, 5, 15, 3, 17, 2, 20, 24, 1, 9, 12, 8};
        findNLargest(arr, 4);
        findNsmallest(arr, 4);
    }

    /**
     * 从数组中找最大的前N个
     *
     * @param nums
     * @param k
     * @return
     */
    public static int findNLargest(int[] nums, int k) {
        PriorityQueue<Integer> minQueue = new PriorityQueue<>(k);
        for (int num : nums) {
            if (minQueue.size() < k || num > minQueue.peek())
                minQueue.offer(num);
            if (minQueue.size() > k)
                minQueue.poll();
        }
        for (; 0 < minQueue.size(); ) {
            System.out.print(minQueue.poll() + ",");
        }
        System.out.println();

        return 0;
    }

    /**
     * 从数组中找出最小的前N个
     *
     * @param nums
     * @param k
     * @return
     */
    public static int findNsmallest(int[] nums, int k) {
        PriorityQueue<Integer> minQueue = new PriorityQueue<>((a, b) -> b - a);
        for (int num : nums) {
            if (minQueue.size() < k || num < minQueue.peek())
                minQueue.offer(num);
            if (minQueue.size() > k)
                minQueue.poll();
        }
        for (; 0 < minQueue.size(); ) {
            System.out.print(minQueue.poll() + ",");
        }
        System.out.println();
        return 0;
    }
}

 

posted @ 2022-02-27 17:29  星星之火可以燎源  阅读(60)  评论(0编辑  收藏  举报