牛客NC88 寻找第K大(优先队列小根堆)

题目
在这里插入图片描述
维护一个长度为K的升序优先队列 大于队首就入队
最后堆顶就是第K大的数

import java.util.*;
public class Solution {
    
    
    public int findKth(int[] a, int n, int K) {
    
    
        PriorityQueue<Integer> queue = new PriorityQueue<Integer>();
        for(int i = 0 ;i < n ;i++){
    
    
            if (queue.size() < K)
                queue.add(a[i]);
            else if (a[i] > queue.peek()){
    
    
                queue.poll();
                queue.add(a[i]);
            }
        }
        return queue.peek();
    }
}

猜你喜欢

转载自blog.csdn.net/qq_43434328/article/details/114971582