Kth Largest in N Arrays

Easy

Find K-th largest element in N arrays.

Notice
You can swap elements in the array

Have you met this question in a real interview? Yes
Example
In n=2 arrays [[9,3,2,4,7],[1,2,3,4,8]], the 3rd largest element is 7.

In n=2 arrays [[9,3,2,4,8],[1,2,3,4,2]], the 1st largest element is 9, 2nd largest element is 8, 3rd largest element is 7 and etc.

这道题用了minHeap, 暴力地将每个数组元素都放到了minHeap里,然后再poll()出来让heap里只剩下k个。从剩下的k个里peek()出来的就是在整个数组里第k大的元素,即为所求。

public class Solution {
    
    /*
     * @param arrays: a list of array
     * @param k: An integer
     * @return: an integer, K-th largest element in N arrays
     */
    public int KthInArrays(int[][] arrays, int k) {
        // write your code here
        PriorityQueue<Integer> pq = new PriorityQueue<>();
        for (int i = 0; i < arrays.length; i++){
            for (int j = 0; j < arrays[i].length; j++){
                pq.add(arrays[i][j]);
            }
        }
        while (pq.size() > k){
            pq.poll();
        }
        return pq.peek();
    }
}

    原文作者:greatfulltime
    原文地址: https://www.jianshu.com/p/4cc399707487
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞