合并 k 个排序链表,返回合并后的排序链表。请分析和描述算法的复杂度。
示例:
输入: [ 1->4->5, 1->3->4, 2->6 ] 输出: 1->1->2->3->4->4->5->6K个有序列表,采用分治方法,两两合并。
时间复杂度是O(nlogK),如果链表数据全部输入到优先队列里,再弹出应该是一样的。
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* mergeKLists(vector<ListNode*>& lists) { int mid=lists.size()/2; ListNode *l1=merge(0,mid-1,lists); ListNode *l2=merge(mid,lists.size()-1,lists); return union_(l1,l2); } ListNode* merge(int st, int ed ,vector<ListNode*>& lists) { if(st==ed) { return lists[st]; } else if(st<ed) { int mid=(st+ed)/2; ListNode *l1=merge(st,mid,lists); ListNode *l2=merge(mid+1,ed,lists); return union_(l1,l2); } else return NULL; } ListNode* union_(ListNode* l1,ListNode* l2) { if(l1==NULL) return l2; if(l2==NULL) return l1; if(l1->val>l2->val) return union_(l2,l1); ListNode *head=l1; while(l2&&l1->next) { if(l1->next->val>l2->val) { ListNode *tmp=l2->next; l2->next=l1->next; l1->next=l2; l2=tmp; } l1=l1->next; } if(l2) l1->next=l2; return head; } };