Skip to content

Commit fb9e520

Browse files
committed
feat: Upload merge-k-sorted-lists (typescript)
1 parent 1744c14 commit fb9e520

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

merge-k-sorted-lists/mike2ox.ts

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
/**
2+
* Source: https://leetcode.com/problems/merge-k-sorted-lists/
3+
* 풀이방법: 모든 리스트들을 한곳에 넣고 재배치
4+
*
5+
* 시간복잡도: O(NlogN) - 모든 리스트를 순회(N), 정렬(NlogN) 하는데 드는 시간 고려
6+
* 공간복잡도: O(N) - 기존 배열을 저장할 공간만 필요
7+
*/
8+
9+
/**
10+
* Definition for singly-linked list.
11+
* class ListNode {
12+
* val: number
13+
* next: ListNode | null
14+
* constructor(val?: number, next?: ListNode | null) {
15+
* this.val = (val===undefined ? 0 : val)
16+
* this.next = (next===undefined ? null : next)
17+
* }
18+
* }
19+
*/
20+
21+
function mergeKLists(lists: Array<ListNode | null>): ListNode | null {
22+
if (!lists?.length) return null;
23+
let merged = [];
24+
25+
for (let i = 0; i < lists.length; i++) {
26+
let cursor = lists[i];
27+
while (cursor != null) {
28+
merged.push(cursor.val);
29+
cursor = cursor.next;
30+
}
31+
}
32+
let sorted = merged.sort((a, b) => (a < b ? -1 : 1));
33+
let head = null;
34+
let tail = null;
35+
36+
for (let i = 0; i < sorted.length; i++) {
37+
const node = new ListNode(sorted[i], null);
38+
if (head === null) {
39+
head = node;
40+
tail = node;
41+
} else {
42+
tail.next = node;
43+
tail = node;
44+
}
45+
}
46+
47+
return head;
48+
}

0 commit comments

Comments
 (0)