File tree Expand file tree Collapse file tree 1 file changed +39
-0
lines changed
Expand file tree Collapse file tree 1 file changed +39
-0
lines changed Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments