Merge K Sorted Arrays

时间:2023-03-09 06:29:11
Merge K Sorted Arrays

This problem can be solved by using a heap. The time is O(nlog(n)).

Given m arrays, the minimum elements of all arrays can form a heap. It takes O(log(m)) to insert an element to the heap and it takes O(log(m)) to delete the minimum element.

 class Record {
int row;
int col;
int val; public Record(int row, int col, int val) {
this.row = row;
this.col = col;
this.val = val;
}
} public class Solution {
public List<Integer> mergekSortedArrays(int[][] arrays) {
PriorityQueue<Record> minHeap = new PriorityQueue<>((x, y) -> x.val - y.val);
for (int i = ; i < arrays.length; i++) {
if (arrays[i].length != ) {
minHeap.offer(new Record(i, , arrays[i][]));
}
} List<Integer> result = new ArrayList<>();
while (!minHeap.isEmpty()) {
Record record = minHeap.poll();
result.add(record.val);
if (record.col + < arrays[record.row].length) {
minHeap.offer(new Record(record.row, record.col + , arrays[record.row][record.col + ]));
}
}
return result;
}
}