-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
28 lines (25 loc) · 947 Bytes
/
index.ts
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
import mergeTwoLists from "../merge-two-sorted-lists/index.ts";
import { ListNode } from "../reverse-linked-list/ListNode.ts";
export default function mergeKLists(
lists: Array<ListNode | null>,
): ListNode | null {
const listsnotnull = lists.filter((a) => !!a) as Array<ListNode>;
if (listsnotnull.length === 0) return null;
if (listsnotnull.length === 1) return listsnotnull[0];
if (listsnotnull.length === 2) {
return mergeTwoLists(listsnotnull[0], listsnotnull[1]);
}
if (listsnotnull.length % 2) {
return mergeTwoLists(
listsnotnull[0],
mergeKLists(listsnotnull.slice(1)),
);
} else {
const half = Math.floor(lists.length / 2) - 1;
return mergeKLists([
mergeKLists(listsnotnull.slice(0, half)),
mergeKLists(listsnotnull.slice(half, half + 2)),
mergeKLists(listsnotnull.slice(half + 2)),
]);
}
}