Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Latest commit

 

History

History
History
72 lines (67 loc) · 1.99 KB

File metadata and controls

72 lines (67 loc) · 1.99 KB
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package problems;
public class LeetCode23 {
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 mergeTwoLists(mergeSort(lists, left, mid), mergeSort(lists, mid + 1, right));
}
private ListNode mergeTwoLists(ListNode a, ListNode b) {
if (a == null || b == null) {
return a != null ? a : b;
}
ListNode head = new ListNode(0);
ListNode tail = head, aPtr = a, bPtr = b;
while (aPtr != null && bPtr != null) {
if (aPtr.val < bPtr.val) {
tail.next = aPtr;
aPtr = aPtr.next;
} else {
tail.next = bPtr;
bPtr = bPtr.next;
}
tail = tail.next;
}
tail.next = (aPtr != null ? aPtr : bPtr);
return head.next;
}
}
/**
* 简单解法:顺序合并
*/
class LeetCode23_1 {
public ListNode mergeKLists(ListNode[] lists) {
ListNode ans = null;
for (int i = 0; i < lists.length; i++) {
ans = mergeTwoLists(ans, lists[i]);
}
return ans;
}
private ListNode mergeTwoLists(ListNode a, ListNode b) {
if(a == null || b == null) {
return a != null ? a:b;
}
ListNode dummyNode = new ListNode(0);
ListNode ptr = dummyNode, aPtr = a, bPtr = b;
while (aPtr != null && bPtr != null) {
if(aPtr.val < bPtr.val) {
ptr.next = aPtr;
aPtr = aPtr.next;
} else {
ptr.next = bPtr;
bPtr = bPtr.next;
}
ptr = ptr.next;
}
ptr.next = (aPtr != null ? aPtr : bPtr);
return dummyNode.next;
}
}
Morty Proxy This is a proxified and sanitized view of the page, visit original site.