方法一:递归分治
使用递归的方法,将数组不断分下去,一分为二,
递归截至条件为,数组中元素为0个,或者1个。
对分治后的两个链表进行合并排序。
分的时间复杂度为O(lgN),合并的时间复杂度为O(N),因此时间复杂度为O(NlgN);
typedef struct ListNode Node;
struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2) {
struct ListNode head;
head.next = NULL;
struct ListNode *rear = &head;
struct ListNode *node = NULL;
while(l1 && l2){
rear->next = l1->val < l2->val ? l1 : l2;
if(l1->val < l2->val){
l1 = l1->next;
}else{
l2 = l2->next;
}
rear = rear->next;
}
if(l1){
rear->next = l1;
}
if(l2){
rear->next = l2;
}
return head.next;
}
struct ListNode* mergeKLists(struct ListNode** lists, int listsSize) {
if(!listsSize){
return NULL;
}
if(listsSize == 1){
return lists[0];
}
int mid = listsSize / 2;
Node *l1 = mergeKLists(lists, mid);
Node *l2 = mergeKLists(lists+mid, listsSize-mid);
return mergeTwoLists(l1, l2);
}
方法二:非递归分治
非递归方法,使用原来的数组,将分治后得到的临时链表头放到数组中,每一个循环数组长度减半,
最后截止到一个元素时,即为要返回的链表头。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
typedef struct ListNode Node;
struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2) {
struct ListNode head;
head.next = NULL;
struct ListNode *rear = &head;
struct ListNode *node = NULL;
while(l1 && l2){
rear->next = l1->val < l2->val ? l1 : l2;
if(l1->val < l2->val){
l1 = l1->next;
}else{
l2 = l2->next;
}
rear = rear->next;
}
if(l1){
rear->next = l1;
}
if(l2){
rear->next = l2;
}
return head.next;
}
struct ListNode* mergeKLists(struct ListNode** lists, int listsSize) {
int left_size = listsSize;
int i, k;
int cnt;
if(!listsSize){
return NULL;
}
while(left_size>1){
k = left_size;
cnt = (k+1)/2;
for(i=0; i= k ? NULL : lists[2*i+1]));
}
left_size = (left_size+1)/2;
}
return lists[0];
}