Topic
Merges the K sorted list and returns the merged sorted list. Try to analyze and describe its complexity.
Sample Example
Give 3 sort list [2->4->null,null,-1->null], return -1->2->4->null
Solving
22 Merging
Merge AB get C
Merge CD get E
/** * Definition for ListNode. * public class ListNode {* int val; * ListNode Next; * ListNode (int val) { * This.val = val; * This.next = null; * } * } */ Public class solution { /** * @param lists:a List of ListNode * @return: The head of one sorted list. */ PublicListNodemergeklists(list<listnode> lists) {//Write your code here if(Lists = =NULL|| Lists.size () = =0)return NULL; ListNode head = Lists.get (0); for(intI=1; I<lists.size (); i++) {ListNode list = Lists.get (i);if(list!=NULL) head = merge (head,list); }//print (head); returnHead } Public void Print(ListNode head) { while(head!=NULL) {System.out.print (Head.val +" ,"); head = Head.next; } System.out.println (); } PublicListNodeMerge(ListNode L1,listnode L2) {if(l1==NULL)returnL2;if(l2==NULL)returnL1; ListNode head =NewListNode (-1); ListNode cur = head; while(l1!=NULL&& l2!=NULL){if(L1.val <=l2.val) {cur.next = L1; L1 = L1.next; }Else{cur.next = L2; L2 = L2.next; } cur = cur.next; }if(l1!=NULL) Cur.next = L1;if(l2!=NULL) Cur.next = L2;returnHead.next; }}
Leveraging priority queues
PublicListNodemergeklists(list<listnode> lists) {//Write your code here if(Lists = =NULL|| Lists.size () = =0)return NULL; ListNode head =NewListNode (0); priorityqueue<listnode> q =NewPriorityqueue<listnode> (Lists.size (),NewComparator<listnode> () { Public int Compare(ListNode A, ListNode b) {if(A.val > B.val)return 1;Else if(A.val = = B.val)return 0;return-1; } }); for(ListNode list:lists) {if(list!=NULL) Q.add (list); } ListNode p = head; while(Q.size () >0) {ListNode tmp = Q.poll (); P.next = tmp;if(tmp.next!=NULL) {Q.add (tmp.next); } p = P.next; }returnHead.next; }
Merging K sorted lists