544. 前K大数

描述

在一个数组中找到前K大的数

样例

给出 [3,10,1000,-99,4,100], k = 3.
返回 [1000, 100, 10]

思路

和上一道题 606. 第K大的元素 II 基本类似,只是本题需要用数组把前k大所有元素输出

代码

class Solution {
    /*
     * @param nums an integer array
     * @param k an integer
     * @return the top k largest numbers in array
     */
     public int[] topk(int[] nums, int k) {
         PriorityQueue minheap = new PriorityQueue(k, new Comparator() {
             public int compare(Integer o1, Integer o2) {
                 return o1 - o2;
             }
         });

         for (int i : nums) {
             minheap.add(i);
             if (minheap.size() > k) {
                minheap.poll();
             }
         }

         int[] result = new int[k];
         // 最小堆抛出顺序是从小到大顺序,结果输出要求是从大到小顺序,
         // 所以要让result[k - 1]等于最小堆第一个抛出的数
         for (int i = 0; i < result.length; i++) {
             result[k - i - 1] = minheap.poll();
         }
         return result;
    }
}

你可能感兴趣的:(544. 前K大数)