topK

public PriorityQueue<Integer> topK(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();
        }
        return minQueue;
    }

    public List<Integer> findTopKLargest(int[] nums, int k)
    {
     
        PriorityQueue<Integer> mQ = topK(nums, k);
        List<Integer> lst = new ArrayList<>();
        while(!mQ.isEmpty())
        {
     
            lst.add(mQ.poll());
        }
        return lst;
    }  

你可能感兴趣的:(topK)