23 Merge k Sorted Lists
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
Solution)
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode mergeList(ListNode l1, ListNode l2) {
if (l1 == null) return l2;
if (l2 == null) return l1;
if (l1.val > l2.val) {
l2.next = mergeList(l1, l2.next);
return l2;
} else {
l1.next = mergeList(l1.next, l2);
return l1;
}
}
public ListNode partition(ListNode[] lists, int s, int e) {
if (s == e) return lists[s];
if (s<e) {
int m = (s+e)/2;
ListNode l1 = partition(lists, s, m);
ListNode l2 = partition(lists, m+1, e);
return mergeList(l1, l2);
} else {
return null;
}
}
public ListNode mergeKLists(ListNode[] lists) {
return partition(lists, 0, lists.length-1);
}
}
Solution 2) Using priority queue,
class Solution {
public ListNode mergeKLists(ListNode[]lists) {
if (lists==null||lists.length==0) return null;
PriorityQueue<ListNode> queue = new PriorityQueue<>((a, b) -> a.val - b.val);
ListNode dummy = new ListNode(0);
ListNode tail=dummy;
for (ListNode node:lists)
if (node!=null)
queue.add(node);
while (!queue.isEmpty()){
tail.next=queue.poll();
tail=tail.next;
if (tail.next!=null)
queue.add(tail.next);
}
return dummy.next;
}
}
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode mergeKLists(ListNode[] lists) {
// using priority queue (mih heap) O(nlogn)
if (lists == null || lists.length == 0) return null;
PriorityQueue<ListNode> queue = new PriorityQueue<>((a,b) -> a.val - b.val);
ListNode dummy = new ListNode(-1);
ListNode tail = dummy;
for (ListNode node : lists)
if (node != null) queue.add(node);
// repeat until queue is empty
while (!queue.isEmpty()) {
tail.next = queue.poll();
tail = tail.next;
if (tail.next != null) queue.add(tail.next);
}
return dummy.next;
}
}