Skip to content

Commit 2e2bf9a

Browse files
committed
Feat: 23. Merge k Sorted Lists
1 parent 1269ea6 commit 2e2bf9a

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

merge-k-sorted-lists/HC-kang.ts

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
// class ListNode {
2+
// val: number;
3+
// next: ListNode | null;
4+
// constructor(val?: number, next?: ListNode | null) {
5+
// this.val = val === undefined ? 0 : val;
6+
// this.next = next === undefined ? null : next;
7+
// }
8+
// }
9+
10+
/**
11+
* https://leetcode.com/problems/merge-k-sorted-lists
12+
* T.C. O(n * k^2) n: average length of list, k: number of lists
13+
* S.C. O(k)
14+
*/
15+
function mergeKLists(lists: Array<ListNode | null>): ListNode | null {
16+
if (lists.length === 0) return null;
17+
if (lists.length === 1) return lists[0];
18+
return lists.reduce((acc, cur) => mergeTwoLists(acc, cur), null);
19+
20+
function mergeTwoLists(list1: ListNode | null, list2: ListNode | null): ListNode | null {
21+
const head = new ListNode();
22+
let current = head;
23+
24+
while (list1 && list2) {
25+
if (list1.val < list2.val) {
26+
current.next = list1;
27+
list1 = list1.next;
28+
} else {
29+
current.next = list2;
30+
list2 = list2.next;
31+
}
32+
current = current.next;
33+
}
34+
35+
current.next = list1 || list2;
36+
37+
return head.next;
38+
}
39+
}

0 commit comments

Comments
 (0)