算法——得到数据流中前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;
    }

 

posted @ 2019-05-11 12:25  高圈圈  阅读(320)  评论(0编辑  收藏  举报