leetcode-Merge k Sorted Lists
题目链接:
https://leetcode.com/problems/merge-k-sorted-lists/
题目分析:
方法1:
可以通过分治法,首先将k条链表,分成两部分,分别对两部分进行合并,直到最后只剩下两条,可以使用merge函数对两条链表进行合并
时间复杂度分析:(待写中)
代码如下:
class Solution { public: ListNode* mergeKLists(vector<ListNode*>& lists) { if(lists.empty()) { return NULL; } return mergeList(lists, 0, lists.size()-1); } private: ListNode* mergeList(vector<ListNode*> &lists, int l, int r) { if(l < r) { int m = (l + r) / 2; ListNode *l1 = mergeList(lists, l, m); ListNode *l2 = mergeList(lists, m+1, r); return mergeList(l1, l2); } else { return lists[l]; } } ListNode *mergeList(ListNode *l1, ListNode *l2) { ListNode dummy(-1); ListNode *p1 = l1; ListNode *p2 = l2; ListNode *p = &dummy; while(p1 != NULL && p2 != NULL) { if(p1->val < p2->val) { p->next = p1; p1 = p1->next; } else { p->next = p2; p2 = p2->next; } p = p->next; } if(p1 != NULL) { p->next = p1; } if(p2 != NULL) { p->next = p2; } return dummy.next; } };
方法2:
利用堆来实现(待写中)