题目描述(困难难度)
原题链接
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
Example:
Input:
[
1->4->5,
1->3->4,
2->6
]
Output: 1->1->2->3->4->4->5->6
算法
(分治)
采用分治算法,例如:n = 6时,合并0-3 1-4 2-5
实现两个有序链表的合并之前已做过
时间复杂度是 :n为链表的个数,m为两个链表结点数的最大值
C++代码
/**
* 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) {
// Divide and Conquer Approach
// odd: n = 5 0-3 1-4 2 k = (n + 1) / 2
// even: n = 6 0-3 1-4 2-5
int n = lists.size();
if (n == 0) return NULL;
while(n > 1) {
int k = (n + 1) / 2;
for (int i = 0; i < n / 2; i ++) {
lists[i] = mergeTwoLists(lists[i], lists[i + k]);
}
n = k;
}
return lists[0];
}
// merge two lists
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
auto dummy = new ListNode(-1);
auto p = dummy;
while(l1 && l2) {
if (l1->val <= l2->val) {
p->next = l1;
p = l1;
l1 = l1->next;
} else {
p->next = l2;
p = l2;
l2 = l2->next;
}
}
if (l1) p->next = l1;
if (l2) p->next = l2;
return dummy->next;
}
};
写在最后:我的博客主要是对计算机领域所学知识的总结、回顾和思考,把每篇博客写得通俗易懂是我的目标,分享技术和知识是一种快乐 ,非常欢迎大家和我一起交流学习,有任何问题都可以在评论区留言,也期待与您的深入交流(^∀^●)