Skip to content

Commit 17d7b0b

Browse files
authored
Merge pull request apachecn#254 from jsycdut/master
提供leetcode 23题-合并K个有序链表的O(NlogK) Java解法
2 parents 73e7642 + 3250987 commit 17d7b0b

File tree

1 file changed

+76
-0
lines changed

1 file changed

+76
-0
lines changed
Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
# 23. Merge K Sorted Lists
2+
3+
*<font color=red>难度: Hard</font>*
4+
5+
## 刷题内容
6+
7+
> 原题链接
8+
9+
https://leetcode.com/problems/merge-k-sorted-lists/description/
10+
11+
> 内容描述
12+
13+
[23] Merge k Sorted Lists
14+
15+
https://leetcode.com/problems/merge-k-sorted-lists/description/
16+
17+
* algorithms
18+
* Hard (33.28%)
19+
* Total Accepted: 352.8K
20+
* Testcase Example: '[[1,4,5],[1,3,4],[2,6]]'
21+
22+
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
23+
24+
Example:
25+
26+
27+
Input:
28+
[
29+
  1->4->5,
30+
  1->3->4,
31+
  2->6
32+
]
33+
34+
## 解题方案
35+
36+
> 思路 1
37+
*****- 时间复杂度:O(NlogK) *****- 空间复杂度:O(N)*****
38+
39+
K为链表的数量,N为所有链表的节点的总个数
40+
41+
此题在于一分一合,将K个有序链表通过二分,拆成两两一组的链表,就变成了leetcode 21题中的合并两个有序链表了,随后将所有链表逐层合并,就像从二叉树的叶子节点开始,不断向上合并,此题就求解完毕了。
42+
43+
此题需要用到的技巧就是二分,以及递归合并两个有序链表(当然迭代合并两个有序列表也是可以的)
44+
45+
Beats 100%
46+
47+
```java
48+
public ListNode mergeKLists(ListNode[] lists) {
49+
if (lists == null || lists.length == 0) return null;
50+
return sort(lists, 0, lists.length - 1);
51+
}
52+
53+
// 二分K个链表
54+
ListNode sort(ListNode[] lists, int lo, int hi) {
55+
if (lo >= hi) return lists[lo];
56+
int mid = (hi -lo) / 2 + lo;
57+
ListNode l1 = sort(lists, lo, mid);
58+
ListNode l2 = sort(lists, mid + 1, hi);
59+
return merge(l1, l2);
60+
}
61+
62+
// 合并两个有序链表的递归写法
63+
ListNode merge(ListNode l1, ListNode l2) {
64+
if (l1 == null) return l2;
65+
if (l2 == null) return l1;
66+
67+
if (l1.val < l2.val) {
68+
l1.next = merge(l1.next, l2);
69+
return l1;
70+
}
71+
72+
l2.next = merge(l2.next, l1);
73+
return l2;
74+
}
75+
76+
```

0 commit comments

Comments
 (0)