Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
Subscribe to see which companies asked this question
Idea: Similar to merge sort, each list is already sorted, now only need to merge each linked list into a list. Point: Divide and conquer, and finally merge.
/** Definition for singly-linked list. * struct ListNode {* int val; * ListNode *next; * ListNode (int x) : Val (x), Next (NULL) {}}; */classSolution {Private: ListNode* MERGE_HELP (Vector<listnode*>&lists,intLintR) { if(l>=R)returnLists[l]; intMid= (L+R)/2; ListNode* left =merge_help (Lists,l,mid); ListNode* RIGHT=MERGE_HELP (lists,mid+1, R); ListNode* Temp =NewListNode (-1); ListNode*cur =temp; while(left&&Right ) { if(left->val<=right->val) {cur->next =Left ; Left=left->Next; } Else{cur->next=Right ; Right=right->Next; } cur=cur->Next; } if(left) cur->next=Left ; if(right) cur->next=Right ; returnTemp->Next; } Public: ListNode* Mergeklists (vector<listnode*>&lists) { if(lists.size () = =0) returnNULL; returnMerge_help (lists,0, Lists.size ()-1); } };
. Merge k Sorted Lists