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(1) to delete the minimum element.
1 package test; 2 3 import java.util.ArrayList; 4 import java.util.HashMap; 5 import java.util.List; 6 import java.util.PriorityQueue; 7 8 class Record { 9 int row; 10 int col; 11 int val; 12 13 public Record(int row, int col, int val) { 14 this.row = row; 15 this.col = col; 16 this.val = val; 17 } 18 } 19 20 public class Solution { 21 public List<Integer> mergekSortedArrays(int[][] arrays) { 22 PriorityQueue<Record> minHeap = new PriorityQueue<Record>(arrays.length, (x, y) -> x.val - y.val); 23 for (int i = 0; i < arrays.length; i++) { 24 if (arrays[i].length != 0) { 25 heap.offer(new Record(i, 0, arrays[i][0])); 26 } 27 } 28 29 List<Integer> result = new ArrayList<>(); 30 while (!minHeap.isEmpty()) { 31 Record record = minHeap.poll(); 32 result.add(record.val); 33 if (record.col + 1 < arrays[record.row].length) { 34 heap.offer(new Record(record.row, record.col + 1, arrays[record.row][record.col + 1])); 35 } 36 } 37 return result; 38 } 39 }