Merge k Sorted Lists
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
思路:
二分转化为两个链表的归并,复杂度为(kn)。
代码:
1 ListNode *merge2Lists(ListNode *l1, ListNode *l2){ 2 if(l1 == NULL) 3 return l2; 4 if(l2 == NULL) 5 return l1; 6 ListNode *result, *head = NULL; 7 if(l1->val < l2->val){ 8 head = l1; 9 l1 = l1->next; 10 } 11 else{ 12 head = l2; 13 l2 = l2->next; 14 } 15 result = head; 16 while(l1 && l2){ 17 if(l1->val < l2->val){ 18 result->next = l1; 19 l1 = l1->next; 20 } 21 else{ 22 result->next = l2; 23 l2 = l2->next; 24 } 25 result = result->next; 26 } 27 if(l1 == NULL) 28 result->next = l2; 29 else 30 result->next = l1; 31 return head; 32 } 33 ListNode *mergeKLists(vector<ListNode *> &lists, int start, int end){ 34 if(start >= end) 35 return NULL; 36 if(end == start+1) 37 return lists[start]; 38 if(end == start+2){ 39 ListNode *l1 = lists[start]; 40 ListNode *l2 = lists[start+1]; 41 return merge2Lists(l1, l2); 42 } 43 else{ 44 ListNode *l1 = mergeKLists(lists, start, (start+end)/2); 45 ListNode *l2 = mergeKLists(lists, (start+end)/2, end); 46 return merge2Lists(l1, l2); 47 } 48 } 49 ListNode *mergeKLists(vector<ListNode *> &lists) { 50 // IMPORTANT: Please reset any member data you declared, as 51 // the same Solution instance will be reused for each test case. 52 return mergeKLists(lists, 0, lists.size()); 53 }
另外一种方法是使用堆,可是使得复杂度变为O(nlgk)。这里堆可以自己实现,也可以用STL中的priority_queue。
在下面代码,一方面要学习priority_queue的使用,另一方面要注意那个虚头head的使用,这样可以避免对head是否为NULL的判断。另外一种解决的类似方法的手段是用一个**指针指向head,然后不断更新**,最后返回**指针指向的指针。
1 struct cmp{ 2 bool operator()(ListNode *a, ListNode *b){ 3 return a->val > b->val; 4 } 5 }; 6 ListNode *mergeKLists(vector<ListNode *> &lists) { 7 // IMPORTANT: Please reset any member data you declared, as 8 // the same Solution instance will be reused for each test case. 9 priority_queue<ListNode*, vector<ListNode*>, cmp > pq; 10 int i; 11 for(i = 0; i < lists.size(); i++){ 12 if(lists[i]) 13 pq.push(lists[i]); 14 } 15 ListNode *head = new ListNode(0), *cur = head; 16 while(!pq.empty()){ 17 ListNode *tmp = pq.top(); 18 cur->next = tmp; 19 cur = cur->next; 20 pq.pop(); 21 if(tmp->next) 22 pq.push(tmp->next); 23 } 24 return head->next; 25 }