23 Merge k Sorted Lists

Last Updated on: January 6, 2021 pm

23 Merge k Sorted Lists - Hard

Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.

Example:

1
2
3
4
5
6
7
Input:
[
1->4->5,
1->3->4,
2->6
]
Output: 1->1->2->3->4->4->5->6

Code

MinHeap

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode mergeKLists(ListNode[] lists) {
if(lists.length == 0 || lists == null)
return null;

Queue<ListNode> q = new PriorityQueue<ListNode>(lists.length,
new Comparator<ListNode>(){
public int compare(ListNode l1, ListNode l2){
return l1.val - l2.val;
}
});

for(int i = 0; i < lists.length; i++){
if(lists[i] != null)
q.offer(lists[i]);
}
ListNode dummy = new ListNode(0);
ListNode cur = dummy;

while(!q.isEmpty()){
ListNode node = q.poll();
cur.next = node;
cur = node;
if(node.next != null){
q.offer(node.next);
}
}

return dummy.next;

}
}