File tree Expand file tree Collapse file tree 2 files changed +44
-0
lines changed Expand file tree Collapse file tree 2 files changed +44
-0
lines changed Original file line number Diff line number Diff line change 25
25
20|[ Valid Parentheses] ( ./0020-valid-parentheses.js ) |Easy|
26
26
21|[ Merge Two Sorted Lists] ( ./0021-merge-two-sorted-lists.js ) |Easy|
27
27
22|[ Generate Parentheses] ( ./0022-generate-parentheses.js ) |Medium|
28
+ 23|[ Merge k Sorted Lists] ( ./0023-merge-k-sorted-lists.js ) |Hard|
28
29
24|[ Swap Nodes in Pairs] ( ./0024-swap-nodes-in-pairs.js ) |Medium|
29
30
27|[ Remove Element] ( ./0027-remove-element.js ) |Easy|
30
31
28|[ Implement strStr()] ( ./0028-implement-strstr.js ) |Easy|
Original file line number Diff line number Diff line change
1
+ /**
2
+ * 23. Merge k Sorted Lists
3
+ * https://leetcode.com/problems/merge-k-sorted-lists/
4
+ * Difficulty: Hard
5
+ *
6
+ * You are given an array of k linked-lists lists, each linked-list is sorted
7
+ * in ascending order.
8
+ *
9
+ * Merge all the linked-lists into one sorted linked-list and return it.
10
+ */
11
+
12
+ /**
13
+ * Definition for singly-linked list.
14
+ * function ListNode(val, next) {
15
+ * this.val = (val===undefined ? 0 : val)
16
+ * this.next = (next===undefined ? null : next)
17
+ * }
18
+ */
19
+ /**
20
+ * @param {ListNode[] } lists
21
+ * @return {ListNode }
22
+ */
23
+ var mergeKLists = function ( lists ) {
24
+ const map = new Map ( ) ;
25
+ for ( let list of lists ) {
26
+ while ( list ) {
27
+ map . set ( list . val , ( map . get ( list . val ) || 0 ) + 1 ) ;
28
+ list = list . next ;
29
+ }
30
+ }
31
+ const sorted = [ ...map ] . sort ( ( [ a ] , [ b ] ) => a - b ) ;
32
+ const result = new ListNode ( ) ;
33
+ let tail = result ;
34
+
35
+ for ( let [ key , value ] of sorted ) {
36
+ while ( value -- ) {
37
+ tail . next = new ListNode ( key ) ;
38
+ tail = tail . next ;
39
+ }
40
+ }
41
+
42
+ return result . next ;
43
+ } ;
You can’t perform that action at this time.
0 commit comments