LeetCode23-合并K个排序链表

题目链接

英文链接:https://leetcode.com/problems/merge-k-sorted-lists/

中文链接:https://leetcode-cn.com/problems/merge-k-sorted-lists/

题目详述

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

示例:

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

题目详解

  • 可以用 PriorityQueue 构建一个大小为 K 的小顶堆。
  • 每次取堆顶元素,同时放入已取出结点的下一个结点。
  • 遍历结点时间复杂度为 O(n),维护堆的时间复杂度为 O(logk),整个时间复杂度为 O(nlogk)。
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
public class LeetCode_00023 {

// 时间复杂度为 O(nlogk)
public ListNode mergeKLists(ListNode[] lists) {
if (lists == null || lists.length == 0) {
return null;
}
PriorityQueue<ListNode> queue = new PriorityQueue<>(lists.length, new Comparator<ListNode>() {
@Override
public int compare(ListNode o1, ListNode o2) {
return Integer.compare(o1.val, o2.val);
}
});
for (ListNode node : lists) {
if (node != null) {
queue.offer(node);
}
}
ListNode dummy = new ListNode(-1);
ListNode cur = dummy;
while (!queue.isEmpty()) {
cur.next = queue.poll();
cur = cur.next;
if (cur.next != null) {
queue.offer(cur.next);
}
}
return dummy.next;
}
}

我们已经知道 LeetCode21-合并两个有序链表 的情况,我们可以借助归并排序的思想,把当前链表序列分成两部分,每部分递归进行合并,然后将左右两部分合并得到的两个链表再进行合并即可。

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
public class LeetCode_00023 {

// 时间复杂度为 O(nlogk)
public ListNode mergeKLists(ListNode[] lists) {
if (lists == null || lists.length == 0) {
return null;
}
return mergeRangeLists(lists, 0, lists.length - 1);
}

private ListNode mergeRangeLists(ListNode[] lists, int lo, int hi) {
if (lo == hi) {
return lists[lo];
}
int mid = lo + (hi - lo) / 2;
ListNode l1 = mergeRangeLists(lists, lo, mid);
ListNode l2 = mergeRangeLists(lists, mid + 1, hi);
return mergeTwoLists(l1, l2);
}

private ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode dummy = new ListNode(-1);
ListNode node = dummy;
while (l1 != null && l2 != null) {
if (l1.val < l2.val) {
node.next = l1;
l1 = l1.next;
} else {
node.next = l2;
l2 = l2.next;
}
node = node.next;
}
if (l1 != null) {
node.next = l1;
}
if (l2 != null) {
node.next = l2;
}
return dummy.next;
}
}