3. 合并K个排序链表
Posted zouma
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了3. 合并K个排序链表相关的知识,希望对你有一定的参考价值。
一、进行k-1次的2路合并,虽然排序次数过多,出现重复排序,但是不得不说 使用迭代的合并内存消耗比递归小很多。O(nk)的时间复杂度,O(1)的空间复杂度
1 ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { 2 if (l1 == nullptr) 3 return l2; 4 else if (l2 == nullptr) 5 return l1; 6 ListNode* temp1 = l1; 7 ListNode* temp2 = l2; 8 ListNode* next1 = nullptr; 9 ListNode* next2 = nullptr; 10 while (temp1 != nullptr&&temp2 != nullptr) 11 { 12 if (temp1->val <= temp2->val && temp1->next) 13 { 14 if (temp1->next->val > temp2->val) 15 { 16 next2 = temp2->next; 17 temp2->next = temp1->next; 18 temp1->next = temp2; 19 temp2 = next2; 20 temp1 = temp1->next; 21 } 22 else if (temp1->next->val <= temp2->val) 23 temp1 = temp1->next; 24 } 25 else if (temp1->val <= temp2->val && !temp1->next) 26 { 27 temp1->next = temp2; 28 break; 29 } 30 else if (temp1->val > temp2->val) 31 { 32 next2 = temp2->next; 33 temp2->next = temp1; 34 temp1 = temp2; 35 temp2 = next2; 36 l1 = temp1; //bug 37 } 38 } 39 return l1; 40 } 41 ListNode* mergeKLists(vector<ListNode*>& lists) 42 { 43 int size = lists.size(); 44 if (size == 0) 45 return nullptr; 46 else if (size == 1) 47 return lists[0]; 48 ListNode* res = mergeTwoLists(lists[0], lists[1]); 49 for (int i = 2; i < size; ++i) 50 { 51 res = mergeTwoLists(res, lists[i]); 52 } 53 return res; 54 }
二、分治(题解里是这么说的?),就是两两配对,O(nlogk)的时间复杂度,O(1)的空间复杂度
1 ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { 2 if (l1 == nullptr) 3 return l2; 4 else if (l2 == nullptr) 5 return l1; 6 ListNode* temp1 = l1; 7 ListNode* temp2 = l2; 8 ListNode* next1 = nullptr; 9 ListNode* next2 = nullptr; 10 while (temp1 != nullptr&&temp2 != nullptr) 11 { 12 if (temp1->val <= temp2->val && temp1->next) 13 { 14 if (temp1->next->val > temp2->val) 15 { 16 next2 = temp2->next; 17 temp2->next = temp1->next; 18 temp1->next = temp2; 19 temp2 = next2; 20 temp1 = temp1->next; 21 } 22 else if (temp1->next->val <= temp2->val) 23 temp1 = temp1->next; 24 } 25 else if (temp1->val <= temp2->val && !temp1->next) 26 { 27 temp1->next = temp2; 28 break; 29 } 30 else if (temp1->val > temp2->val) 31 { 32 next2 = temp2->next; 33 temp2->next = temp1; 34 temp1 = temp2; 35 temp2 = next2; 36 l1 = temp1; //bug 37 } 38 } 39 return l1; 40 } 41 ListNode* mergeKLists(vector<ListNode*>& lists) 42 { 43 int size = lists.size(); 44 if (size == 0) 45 return nullptr; 46 else if (size == 1) 47 return lists[0]; 48 int k = size; 49 50 int distance = 1; 51 while (distance<size) 52 { 53 for (int i = 0; i < size; i=i+distance*2) 54 { 55 if(i+distance<size) //bug 56 lists[i] = mergeTwoLists(lists[i], lists[i + distance]); 57 } 58 distance *= 2; 59 } 60 return lists[0]; 61 }
以上是关于3. 合并K个排序链表的主要内容,如果未能解决你的问题,请参考以下文章