Skip to content

Commit 97e10ba

Browse files
committed
add Merge k Sorted Lists solution
1 parent 4db8165 commit 97e10ba

File tree

1 file changed

+101
-0
lines changed

1 file changed

+101
-0
lines changed
Lines changed: 101 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,101 @@
1+
/**
2+
* [Problem]: [23] Merge k Sorted Lists
3+
* (https://leetcode.com/problems/merge-k-sorted-lists/description/)
4+
*/
5+
6+
class ListNode {
7+
val: number;
8+
next: ListNode | null;
9+
constructor(val?: number, next?: ListNode | null) {
10+
this.val = val === undefined ? 0 : val;
11+
this.next = next === undefined ? null : next;
12+
}
13+
}
14+
15+
function mergeKLists(lists: Array<ListNode | null>): ListNode | null {
16+
//시간복잡도: O(n log n)
17+
//공간복잡도: O(n)
18+
function bruteForceFunc(lists: Array<ListNode | null>): ListNode | null {
19+
const arr: number[] = [];
20+
let dummy = new ListNode(0);
21+
let current = dummy;
22+
23+
if (!lists.length) return null;
24+
25+
for (let i = 0; i < lists.length; i++) {
26+
let currentNode = lists[i];
27+
while (currentNode) {
28+
arr.push(currentNode.val);
29+
currentNode = currentNode.next;
30+
}
31+
}
32+
33+
arr.sort((a, b) => a - b);
34+
35+
for (let j = 0; j < arr.length; j++) {
36+
current.next = new ListNode(arr[j]);
37+
current = current.next;
38+
}
39+
40+
return dummy.next;
41+
}
42+
43+
//시간복잡도: O(nk)
44+
//공간복잡도: O(n)
45+
function mergeFunc(lists: Array<ListNode | null>): ListNode | null {
46+
let dummy = new ListNode(0);
47+
let cur = dummy;
48+
49+
while (lists.some((node) => node !== null)) {
50+
let minVal = Infinity;
51+
let minIdx = -1;
52+
53+
for (let i = 0; i < lists.length; i++) {
54+
if (lists[i] && lists[i]!.val < minVal) {
55+
minVal = lists[i]!.val;
56+
minIdx = i;
57+
}
58+
}
59+
60+
if (minIdx !== -1) {
61+
cur.next = new ListNode(minVal);
62+
cur = cur.next;
63+
lists[minIdx] = lists[minIdx]!.next;
64+
}
65+
}
66+
67+
return dummy.next;
68+
}
69+
//시간복잡도: O(n log k)
70+
//공간복잡도: O(log k)
71+
function divideAndConqureFunc(lists: Array<ListNode | null>): ListNode | null {
72+
if (!lists.length) return null;
73+
if (lists.length === 1) return lists[0];
74+
75+
const mid = Math.floor(lists.length / 2);
76+
const left = divideAndConqureFunc(lists.slice(0, mid));
77+
const right = divideAndConqureFunc(lists.slice(mid));
78+
79+
function mergeTwoLists(list1: ListNode | null, list2: ListNode | null): ListNode | null {
80+
const dummy = new ListNode(-1);
81+
let cur = dummy;
82+
83+
while (list1 && list2) {
84+
if (list1.val < list2.val) {
85+
cur.next = list1;
86+
list1 = list1.next;
87+
} else {
88+
cur.next = list2;
89+
list2 = list2.next;
90+
}
91+
92+
cur = cur.next;
93+
}
94+
95+
cur.next = list1 ?? list2;
96+
return dummy.next;
97+
}
98+
99+
return mergeTwoLists(left, right);
100+
}
101+
}

0 commit comments

Comments
 (0)