Title Description
Merge k sorted lists to return the merged sorted list. Please analyze and describe the complexity of the algorithm.
thinking
- First, traverse all the linked lists, save the corresponding values in the array, and then traverse the array to create a new linked list
- Divide and Conquer: each linked list is fused with the next linked list first, so that the total number of linked lists will be from k to k/2, repeat until the total number of linked lists is 1, and return to the head pointer
Code
Method 1:
class Solution { public: ListNode* mergeKLists(vector<ListNode*>& lists) { if(lists.size()==0) return NULL; vector<int> res; for(int i = 0; i < lists.size();i++) { ListNode* head = lists[i]; while(head!=NULL) { res.push_back(head->val); head = head->next; } } if(res.size()==0) return NULL; sort(res.begin(),res.end()); ListNode* res_head = new ListNode(res[0]); ListNode* cur = res_head; for(int i = 1;i<res.size();i++) { ListNode* next = new ListNode(res[i]); cur->next = next; cur = cur->next; } return res_head; } };
Method two:
class Solution { public: ListNode* mergeKLists(vector<ListNode*>& lists) { if(lists.size()==0) return NULL; while(lists.size()>1) { int size = lists.size(); int i = 0; for(; i < size ;i=i+2) { if(i+1 <size) { if(lists[i] && lists[i+1]) /*Judge whether the head is empty. If it is not empty, merge it. If it is empty, press in it. If it is empty, skip it*/ { if(lists[i]->val >lists[i+1]->val) lists.push_back(mergeTwoLists(lists[i+1],lists[i])); else lists.push_back(mergeTwoLists(lists[i],lists[i+1])); } else if(lists[i] == NULL && lists[i+1]) lists.push_back(lists[i+1]); else if(lists[i+1] == NULL && lists[i]) lists.push_back(lists[i]); } } if(size%2==0) lists.erase(lists.begin(),lists.begin()+size); else lists.erase(lists.begin(),lists.begin()+size-1); } return lists[0]; } ListNode* mergeTwoLists(ListNode* l1,ListNode* l2) { ListNode* res_head = l1; ListNode* cur = res_head; l1 = l1->next; while(l1 != NULL || l2 !=NULL) { if(l1 == NULL) { cur->next = l2; break; } else if(l2 == NULL) { cur->next = l1; break; } else { if(l1->val > l2->val) { cur->next = l2; l2 = l2->next; } else { cur->next = l1; l1 = l1->next; } cur = cur->next; } } return res_head; } };