Skip to content

Commit c5544a8

Browse files
committed
merge-k-sorted-lists solution
1 parent d5e98d4 commit c5544a8

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

merge-k-sorted-lists/jdy8739.js

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* function ListNode(val, next) {
4+
* this.val = (val===undefined ? 0 : val)
5+
* this.next = (next===undefined ? null : next)
6+
* }
7+
*/
8+
/**
9+
* @param {ListNode[]} lists
10+
* @return {ListNode}
11+
*/
12+
var mergeKLists = function (lists) {
13+
const arr = [];
14+
15+
for (let i = 0; i < lists.length; i++) {
16+
let list = lists[i];
17+
18+
while (list) {
19+
arr.push(list.val);
20+
list = list.next;
21+
}
22+
}
23+
24+
if (!arr.length) {
25+
return null;
26+
}
27+
28+
arr.sort((a, b) => a - b);
29+
30+
const first = new ListNode(arr[0]);
31+
32+
let node = first;
33+
34+
for (let j = 1; j < arr.length; j++) {
35+
const next = new ListNode(arr[j]);
36+
node.next = next;
37+
node = next;
38+
}
39+
40+
return first;
41+
};
42+
43+
// 시간복잡도 -> for문 이후 sort 이후 for문을 수행하며 이는 O(n) + O(nlogn) + O(n)이므로 O(nlogn)가 시간복잡도가 된다
44+
// 공간복잡도 -> lists의 노드 수 만큼 길이가 결정되므로 0(n)

0 commit comments

Comments
 (0)