在N个数组中找到第K大元素
样例
例1:
输入:
n=2,[[9,3,2,4,7],[1,2,3,4,8]]
输出:
7
解释:
第三大的元素为 7。
例2:
输入:
n=2,[[9,3,2,4,8],[1,2,3,4,2]]
输出:
8
解释:
最大的元素为 9,第二大的元素为 8,第三大的元素为 4 等等。
注意事项
你可以交换数组中的元素
解题思路:
优先队列
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> queue = new PriorityQueue<>(11, Collections.reverseOrder());
for(int i=0; i<arrays.length; i++)
for(int j=0; j<arrays[i].length; j++)
queue.offer(arrays[i][j]);
while(--k != 0)
queue.poll();
return queue.peek();
}
}