Skip to content

Commit cfa4c54

Browse files
committed
5. Merge k Sorted Lists
1 parent f4b3dc4 commit cfa4c54

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

merge-k-sorted-lists/sunjae95.js

+43
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
/**
2+
* @description
3+
* queue의 특성을 활용하여 풀이
4+
*
5+
* n = length of lists
6+
* m = length of lists[i]
7+
* time complexity: O(n * n * m)
8+
* space complexity: O(n*m)
9+
*/
10+
var mergeKLists = function (lists) {
11+
let answer = null;
12+
let tail = null;
13+
let totalSize = lists.reduce((size, list) => {
14+
let head = list;
15+
let count = 0;
16+
17+
while (head) {
18+
head = head.next;
19+
count++;
20+
}
21+
22+
return size + count;
23+
}, 0);
24+
25+
while (totalSize--) {
26+
let minIndex = lists.reduce((acc, list, i) => {
27+
if (list === null) return acc;
28+
if (acc === null) return { value: list.val, index: i };
29+
return acc.value < list.val ? acc : { value: list.val, index: i };
30+
}, null).index;
31+
32+
if (answer === null) {
33+
answer = lists[minIndex];
34+
tail = answer;
35+
} else {
36+
tail.next = lists[minIndex];
37+
tail = lists[minIndex];
38+
}
39+
40+
lists[minIndex] = lists[minIndex].next;
41+
}
42+
return answer;
43+
};

0 commit comments

Comments
 (0)