标签:
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
合并k个有序链表。
此题的思路类似归并排序,而归并排序有两种思路,一种是从上往下递归,一种是从下往上迭代,这里选择后者,每次迭代合并相邻的两个链表,最后当链表个数为1时返回这个链表。时间复杂度是O(n*logk),n是链表的平均长度,代码如下:
ListNode* merge2(ListNode* l1, ListNode* l2); ListNode* mergeKLists(vector<ListNode*>& lists) { int n = lists.size(); if (0==n) return NULL; for (int len=1; len<n; len*=2) { for (int i=0; i+len<n; i+=len*2) lists[i] = merge2(lists[i], lists[i+len]); } return lists[0]; } ListNode* merge2(ListNode* l1, ListNode* l2) { ListNode fake_head(0); ListNode* p = &fake_head; while (l1!=NULL && l2!=NULL) { if (l1->val <= l2->val) { p->next = l1; p = p->next; l1 = l1->next; } else { p->next = l2; p = p->next; l2 = l2->next; } } p->next = (l1!=NULL)?l1:l2; return fake_head.next; }
标签:
原文地址:http://www.cnblogs.com/zhiguoxu/p/5467866.html