. Merge k Sorted Lists
- Total accepted:92690
- Total submissions:385821
- Difficulty:hard
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
Ideas:
You can do 21 first. Merge Sorted Lists.
Method One: Each recursion merges the first 2 lists in the lists until the merge has only 1 lists left.
Method Two: Merge, after each merger, lists scale reduced by half.
Note that variables in local functions are generally initialized first!
Code:
Method One:
1 /**2 * Definition for singly-linked list.3 * struct ListNode {4 * int val;5 * ListNode *next;6 * ListNode (int x): Val (x), Next (NULL) {}7 * };8 */9 classSolution {Ten Public: Onelistnode* mergetwolists (listnode* a,listnode*b) { A if(!a) { - returnb; - } the if(!b) { - returnA; - } - if(a->val>b->val) { +B->next=mergetwolists (a,b->next); - returnb; + } AA->next=mergetwolists (a->next,b); at returnA; - } -listnode* mergeklists (vector<listnode*>&lists) { -listnode* Head=null;//be sure to initialize!! - while(Lists.size () >1){ -Lists.push_back (Mergetwolists (lists[0],lists[1])); in lists.erase (Lists.begin ()); - lists.erase (Lists.begin ()); to } + if(Lists.size ()) { -head=lists[0]; the } * returnhead; $ }Panax Notoginseng};
Method Two:
1 /**2 * Definition for singly-linked list.3 * struct ListNode {4 * int val;5 * ListNode *next;6 * ListNode (int x): Val (x), Next (NULL) {}7 * };8 */9 classSolution {Ten Public: Onelistnode* mergetwolists (listnode* a,listnode*b) { A if(!a) { - returnb; - } the if(!b) { - returnA; - } - if(a->val>b->val) { +B->next=mergetwolists (a,b->next); - returnb; + } AA->next=mergetwolists (a->next,b); at returnA; - } -listnode* mergeklists (vector<listnode*>&lists) { - if(Lists.empty ()) { - returnNULL; - } in intlen=lists.size (); - intb=0, e=len-1; to while(b<D) { + while(b<e) { -lists[b]=mergetwolists (Lists[b],lists[e]); theb++; *e--; $ }Panax Notoginsengb=0; - } the returnlists[0]; + } A};
Or
1 classSolution {2 Public:3listnode* mergetwolists (listnode* a,listnode*b) {4 if(!a) {5 returnb;6 }7 if(!b) {8 returnA;9 }Ten if(a->val>b->val) { OneB->next=mergetwolists (a,b->next); A returnb; - } -A->next=mergetwolists (a->next,b); the returnA; - } -listnode* mergeklists (vector<listnode*>&lists) { -Vector<listnode*>Res; + inti; - for(i=0; I<lists.size (); i++){ + if(Lists[i]) { A Res.push_back (Lists[i]); at } - } - if(!res.size ()) { - returnNULL; - } - intlen=res.size (); in while(len>1){ - //set len=2q or 2q+1 to for(i=0; i<len/2; i++) {//Note Whether Len is an odd or even number of cases +Res[i]=mergetwolists (res[i],res[len-1-i]); - } the //this time Len should be equal to Q (Len is even) or q+1 (Len is odd) *Len= (len+1)/2; $ }Panax Notoginseng returnres[0]; - } the};
Leetcode 23. Merge k Sorted Lists