Question
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
Solution 1--Merge Sort
We can follow the method of the merge sort. Time Complexity O (Nlog (n)), n is the total number of all nodes.
1 /**2 * Definition for singly-linked list.3 * public class ListNode {4 * int val;5 * ListNode Next;6 * ListNode (int x) {val = x;}7 * }8 */9 Public classSolution {Ten PublicListNode mergeklists (listnode[] lists) { One if(Lists = =NULL|| Lists.length < 1) A return NULL; - if(Lists.length = = 1) - returnLists[0]; the intK =lists.length; - returnMsort (lists, 0, k-1); - } - + PrivateListNode Msort (listnode[] lists,intStartintend) { - if(Start <end) { + intMid = (End-start)/2 +start; AListNode left =msort (lists, start, mid); atListNode right = Msort (lists, Mid + 1, end); - returnmergetwolists (left, right); - } - returnLists[start]; - } - in PrivateListNode mergetwolists (ListNode A, ListNode b) { -ListNode Newhead =NewListNode (0); toListNode p = newhead, p1 = A, p2 =b; + while(P1! =NULL&& P2! =NULL) { - if(P1.val <p2.val) { theP.next =NewListNode (p1.val); *P1 =P1.next; $}Else {Panax NotoginsengP.next =NewListNode (p2.val); -P2 =P2.next; the } +p =P.next; A } the while(P1! =NULL) { +P.next =NewListNode (p1.val); -P1 =P1.next; $p =P.next; $ } - while(P2! =NULL) { -P.next =NewListNode (p2.val); theP2 =P2.next; -p =P.next;Wuyi } the returnNewhead.next; - } Wu}Solution 2--Priorityqueue
We can use the Priorityqueue in Java. The elements of the priority queue is ordered according to their natural ordering, or by a comparator provided at the con Struction time.
Priorityqueue
Comparator
1 /**2 * Definition for singly-linked list.3 * public class ListNode {4 * int val;5 * ListNode Next;6 * ListNode (int x) {val = x;}7 * }8 */9 Public classSolution {Ten PublicListNode mergeklists (listnode[] lists) { One if(Lists = =NULL|| Lists.length < 1) A return NULL; -ListNode Newhead =NewListNode (0); -Priorityqueue<listnode> PQ =NewPriorityqueue<listnode>(Lists.length, the NewComparator<listnode>() { - Public intCompare (ListNode A, ListNode b) { - return(A.val-b.val); - }}); + for(ListNode tmp:lists) { - if(TMP! =NULL) + Pq.add (TMP); A } atListNode p =Newhead; - while(Pq.size () > 0) { -ListNode tmp =Pq.poll (); -P.next =tmp; - if(Tmp.next! =NULL) - Pq.add (tmp.next); inp =P.next; - } to returnNewhead.next; + } -}
Merge k Sorted Lists Solution