Fork me on GitHub

23.合并k个排序链表

题目描述

合并 k 个排序链表,返回合并后的排序链表。请分析和描述算法的复杂度。

示例:

输入:
[
  1->4->5,
  1->3->4,
  2->6
]
输出: 1->1->2->3->4->4->5->6

解决方案

我们采用二分法与迭代法来解决该问题,每次讲两个链表合并成一个链表后,将得到的新链表继续进行与下一个链表进行合并,具体代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* mergeTwoList(ListNode* l1,ListNode* l2){
ListNode *node = new ListNode(-1);
ListNode *cur = node;

while(l1&&l2){
if(l1->val < l2->val){
cur->next = l1;
l1 = l1->next;
}else{
cur->next = l2;
l2 = l2->next;
}
cur = cur->next;
}
if(l1) cur->next = l1;
if(l2) cur->next = l2;
return node->next;
}

ListNode* mergeKLists(vector<ListNode*>& lists) {
if(lists.size() ==0){
return NULL;
}
if(lists.size()==1){
return lists[0];
}

int len = lists.size();
while(len>1){
int n = (len+1)/2;
for(int i=0;i<len/2;++i){
lists[i] = mergeTwoList(lists[i],lists[i+n]);
}
len = n;
}

return lists[0];
}
};

本文标题:23.合并k个排序链表

文章作者:LiuXiaoKun

发布时间:2019年02月25日 - 23:02

最后更新:2019年02月25日 - 23:02

原始链接:https://LiuZiQiao.github.io/2019/02/25/23-合并k个排序链表/

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。

0%