Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
Example:
Input: [ 1->4->5, 1->3->4, 2->6 ] Output: 1->1->2->3->4->4->5->6
Solution 1:
Since k linked lists are sorted, so the head of new list must be one of first element of each linked list. Since each chosen listnode need one time comparasion among k listnode, we can use priorityqueue to pick a smallest node. After that, new listnode is inserted into pq, which takes O(logk). Every time picking a listnode into new linkedlist takes O(logk) time. We have k * n listnodes. So total time complexity is O(nklogk). Space complexity is the size of pq, which is O(k).
Code:
public ListNode mergeKLists(ListNode[] lists) {
if (lists == null || lists.length == 0) {
return null;
}
PriorityQueue<ListNode> pq = new PriorityQueue<>(lists.length, new Comparator<ListNode>(){
public int compare(ListNode l1, ListNode l2) {
return l1.val - l2.val;
}
});
ListNode dummy = new ListNode(-1);
ListNode pre = dummy;
for (ListNode node: lists) {
if (node == null) continue;
pq.offer(node);
}
while (pq.size() != 0) {
ListNode cur = pq.poll();
if (cur.next != null) {
pq.offer(cur.next);
}
pre.next = cur;
pre = pre.next;
}
return dummy.next;
}
Solution 2: Divide and Conquer
The idea is similiar to mergeSort. We divide a task into two subtasks, use recursion to deal with two subtasks to get result of each subtask, then use the same way to get result of original task. In this problem, we divide k lists into two k/2 lists, continuously divide lists until two single list left, then merge two single list, continuously merge until get the result list. We have two ways to calculate time complexity. 1. Merging two single linkedlist takes O(len1 + len2) --------len1 and len2 is the length of two single list-------so that at each level when we do merge, we need O(k*n), how many level we have? logk, because k list at first merge level, 1 list at last merge level, merge two sorted linkedlist each time. Total time complexity is O*(nklogk). 2. T(k) = 2T(k/2) + O(nk), so time complexity is O(nklogk).
Code:
public ListNode mergeKLists(ListNode[] lists) {
if (lists == null || lists.length == 0) {
return null;
}
return divide(lists, 0, lists.length - 1);
}
private ListNode divide(ListNode[] lists, int start, int end) {
if (start == end) {
return lists[start];
}
int mid = start + (end - start) / 2;
ListNode lsub = divide(lists, start, mid);
ListNode rsub = divide(lists, mid + 1, end);
return merge(lsub, rsub);
}
private ListNode merge(ListNode l1, ListNode l2) {
ListNode dummy = new ListNode(-1);
ListNode pre = dummy;
while (l1 != null && l2 != null) {
if (l1.val < l2.val) {
pre.next = l1;
l1 = l1.next;
} else {
pre.next = l2;
l2 = l2.next;
}
pre = pre.next;
}
if (l1 != null) {
pre.next = l1;
}
if (l2 != null) {
pre.next = l2;
}
return dummy.next;
}