Hi all,
I learned this technique from a mock interview with my friend.
instead of min heap, we can use a max heap and adjust the priority queue to only contain k elements.
then your kth smallest element at the end is just the first one to come out from the priority queue.
public static int findKthSmallest(List<Integer[]> lists, int k) {
Queue<Integer> pq = new PriorityQueue<>(Collections.reverseOrder());
for (Integer[] arr : lists) {
for (int i = 0; i < arr.length; ++i) {
pq.offer(arr[i]);
if (pq.size() > k) {
pq.poll();
}
}
}
return pq.poll();
}