p23

LeetCode 21 Merge k Sorted Lists 题解

1.题目:

Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.

题意:

合并K个有序链表

2.解题思路:

用21题的方法,加上递归,两两合并再合并。

3.代码


[title] [] [url] [link text]
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
50
51
52
53
54
55
 

public class Solution {
public static ListNode mergeKLists(ListNode[] lists) {
ListNode ans = new ListNode(Integer.MIN_VALUE);

// ListNode node = ans;
int len = lists.length;
if (len < 1)
return null;
if (len == 1)
return lists[0];

return mergeKLists(lists, 0, len - 1);
}

public static ListNode mergeKLists(ListNode[] lists, int left, int right) {
if (left == right)
return lists[left];
ListNode ans = new ListNode(Integer.MIN_VALUE);

int mid = (left + right) / 2;
return mergeTwoLists(mergeKLists(lists, left, mid),
mergeKLists(lists, mid + 1, right));// 用递归不然会超时
}

public static ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if (l1 == null) {
return l2;
}
if (l2 == null) {
return l1;
}
ListNode ans = new ListNode(0);

ListNode node = ans;

while (l1 != null && l2 != null) {
if (l1.val >= l2.val) {
node.next = l2;

l2 = l2.next;
} else {
node.next = l1;
l1 = l1.next;
}
// System.out.println(node.val);
node = node.next;
}
node.next = (l1 != null) ? l1 : l2;

return ans.next;
}
}


4.一些总结: