Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
#include<iostream> #include<vector> using namespace std; struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; class Solution { public: ListNode *mergeKLists(vector<ListNode *> &lists) { int lSize= lists.size(); if(lSize == 0) return NULL; else if(lSize == 1) return lists[0]; for(int i=1;i<lSize;i++) { lists[0] = Merge(lists[0],lists[i]); } return lists[0]; } private: ListNode* Merge(ListNode *list1,ListNode *list2) { ListNode *head = new ListNode(0); ListNode *p = head; ListNode *l1 = list1,*l2 = list2; while(l1!=NULL && l2 !=NULL) { if(l1->val < l2->val) { p->next = l1; l1 = l1->next; p = p->next; } else { p->next = l2; l2 = l2->next; p = p->next; } } while(l1 != NULL) { p->next = l1; l1 = l1->next; p = p->next; } while(l2 != NULL) { p->next = l2; l2 = l2->next; p = p->next; } p->next = NULL; return head->next; } };
思路:第0个List和第1个Merge,将结果写入第0个,然后第0个和第2个Merge,将结果写入第0个,依次进行。
每次两两Merge都将结果写入第0个这样做避免了用额外的空间。