23. 合并K个升序链表(一般)

给你一个链表数组,每个链表都已经按升序排列。

请你将所有链表合并到一个升序链表中,返回合并后的链表。

示例 1:

1
2
3
4
5
6
7
8
9
10
输入:lists = [[1,4,5],[1,3,4],[2,6]]
输出:[1,1,2,3,4,4,5,6]
解释:链表数组如下:
[
1->4->5,
1->3->4,
2->6
]
将它们合并到一个有序链表中得到。
1->1->2->3->4->4->5->6

示例 2:

1
2
3
4
5
6
输入:lists = []
输出:[]
示例 3:

输入:lists = [[]]
输出:[]

提示:

1
2
3
4
5
6
k == lists.length
0 <= k <= 10^4
0 <= lists[i].length <= 500
-10^4 <= lists[i][j] <= 10^4
lists[i] 按 升序 排列
lists[i].length 的总和不超过 10^4

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/merge-k-sorted-lists

思路1:

需要先了解合并两个有序链表–leetcode21

然后我们直接顺序合并

用一个变量res来维护已经合并的链表,剩下的俩表,按序和res来合并,当循环结束,返回res即可

思路2

还是合并两个有序链表,但是后面我们不按序合并,我们两个归并进行

https://leetcode-cn.com/problems/merge-k-sorted-lists/solution/he-bing-kge-pai-xu-lian-biao-by-leetcode-solutio-2/

代码2:

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
class Solution {
public ListNode mergeKLists(ListNode[] lists) {
//归并排序
return merge(lists,0, lists.length-1);
}
ListNode merge(ListNode[] lists,int left,int right){
if (left==right){
return lists[left];
}
if(left>right){
return null;
}
int mid = (right+left)>>1;
return mergeTwoLists(merge(lists,left,mid),merge(lists,mid+1,right));
}

//合并两个有序链表
ListNode mergeTwoLists(ListNode l1,ListNode l2){
if(l1==null || l2==null){
return l1!=null?l1:l2;
}
ListNode head = new ListNode();
ListNode dummyNode = head;
while (l1!=null && l2!=null){
if(l1.val<=l2.val){
head.next = l1;
l1 = l1.next;
}else {
head.next = l2;
l2 = l2.next;
}
head = head.next;
}
head.next = l1!=null?l1:l2;
return dummyNode.next;
}
}