Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
If you traverse a list of linked lists directly, the time complexity is T (n) =t (n-1) +o (Lenn); the time + and nth linked list length of the n-1 list before merging
Can be used to merge the idea to do, the time complexity of t (n) = 2T (N/2) + O (totallen);
/** Definition for singly-linked list. * struct ListNode {* int val; * ListNode *next; * ListNode (int x) : Val (x), Next (NULL) {}}; */classSolution { Public: ListNode* Mergetwolists (listnode* l1,listnode*L2) { if(l1==NULL) { returnL2; } if(l2==NULL) { returnL1; } ListNode* head = L1->val<l2->val?L1:l2; if(head==L1) {Head->next = Mergetwolists (l1->next,l2); }Else{Head->next = Mergetwolists (l1,l2->next); } returnHead; } ListNode* Mergeklists (vector<listnode*>& lists,intStartintend) { if(Start >=end) { returnNULL; } if(start+1==end) { returnLists[start]; } intMID = start + (End-start)/2 ; ListNode* L1 =mergeklists (Lists,start,mid); ListNode* L2 =mergeklists (lists,mid,end); returnmergetwolists (L1,L2); } ListNode* Mergeklists (vector<listnode*>&lists) { intListssize =lists.size (); returnMergeklists (lists,0, listssize); }};
Merge k Sorted Lists