Method One: Time complexity O (m1 + m2 +: m2), timed out
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* mergeklists (vector<listnode*>&lists) {
Pay attention to the empty situation here [[]] A //finding the least-valued node -listnode* ptr =nullptr; -listnode* Phead =ptr; the if(lists.size () = =0)returnPhead; - Else { - intMinindex =-1; - for(inti =0; I < lists.size (); ++i) { + if(Lists[i]! =nullptr) { - if(Minindex = =-1) Minindex =i; + Else { A if(Lists[i]->val < lists[minindex]->val) Minindex =i; at } - } - } - if(Minindex! =-1) { -PTR =Lists[minindex]; -Lists[minindex] = lists[minindex]->Next; in } - //cout << ptr->val << Endl; toPhead = ptr;//Head Pointer + BOOLFlag =false;//determine if all the points are sorted - while(!flag) { theFlag =true; * intindex =-1;//Record the minimum node subscript $ for(inti =0; I < lists.size (); ++i) {Panax Notoginseng if(Lists[i]! =nullptr) { -Flag =false; the if(Index = =-1) index =i; + Else { A if(Lists[i]->val < lists[index]->val) index =i; the } + } - } $ $ if(Index! =-1) { - //cout << lists[index]->val << Endl; -Ptr->next =Lists[index]; thePTR = ptr->Next; -Lists[index] = lists[index]->Next;Wuyi } the } - returnPhead; Wu } - } About};
Method Two:
023. Merge k Sorted Lists