算法——得到数据流中前K大的数

Posted gaoquanquan

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了算法——得到数据流中前K大的数相关的知识,希望对你有一定的参考价值。

用优先队列

    public PriorityQueue<Integer> kthLargest(int k, int[]a) {
        PriorityQueue<Integer> q = new PriorityQueue<>(k);
        for (int i : a) {
            if (q.size() < k) {
                q.offer(i);
            }else {
                if (i > q.peek()) {
                    q.poll();
                    q.offer(i);
                }
            }
        }
        return q;
    }

 

以上是关于算法——得到数据流中前K大的数的主要内容,如果未能解决你的问题,请参考以下文章