Skip to content

Commit f678e70

Browse files
committed
Add solution #23
1 parent 474b112 commit f678e70

File tree

2 files changed

+44
-0
lines changed

2 files changed

+44
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@
2525
20|[Valid Parentheses](./0020-valid-parentheses.js)|Easy|
2626
21|[Merge Two Sorted Lists](./0021-merge-two-sorted-lists.js)|Easy|
2727
22|[Generate Parentheses](./0022-generate-parentheses.js)|Medium|
28+
23|[Merge k Sorted Lists](./0023-merge-k-sorted-lists.js)|Hard|
2829
24|[Swap Nodes in Pairs](./0024-swap-nodes-in-pairs.js)|Medium|
2930
27|[Remove Element](./0027-remove-element.js)|Easy|
3031
28|[Implement strStr()](./0028-implement-strstr.js)|Easy|
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
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+
};

0 commit comments

Comments
 (0)