-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathMain23.java
More file actions
44 lines (41 loc) · 1.13 KB
/
Main23.java
File metadata and controls
44 lines (41 loc) · 1.13 KB
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
package HOT100;
public class Main23 {
public ListNode mergeKLists(ListNode[] lists) {
int n = lists.length;
return MergeSort(lists, 0, n - 1);
}
private ListNode MergeSort(ListNode[] lists, int left, int right) {
if(left == right) {
return lists[left];
}
if(left > right) {
return null;
}
int mid = (left + right) / 2;
return MergeTwoList(MergeSort(lists, left ,mid), MergeSort(lists, mid + 1, right));
}
private ListNode MergeTwoList(ListNode a, ListNode b) {
if (a == null || b == null) {
return a != null ? a : b;
}
ListNode dummy = new ListNode(-1);
ListNode temp = dummy;
while (a != null && b != null) {
if(a.val <= b.val) {
temp.next = a;
a = a.next;
} else {
temp.next =b;
b = b.next;
}
temp = temp.next;
}
if(a != null) {
temp.next = a;
}
if(b != null) {
temp.next = b;
}
return dummy.next;
}
}