-
Notifications
You must be signed in to change notification settings - Fork 125
/
Copy pathmmyeon.ts
61 lines (50 loc) ยท 1.54 KB
/
mmyeon.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
class ListNode {
val: number;
next: ListNode | null;
constructor(val?: number, next?: ListNode | null) {
this.val = val === undefined ? 0 : val;
this.next = next === undefined ? null : next;
}
}
/**
* @link https://leetcode.com/problems/merge-k-sorted-lists/description/
*
* ์ ๊ทผ ๋ฐฉ๋ฒ :
* - ๋ฆฌ์คํธ๋ฅผ ๋ฐฐ์ด์ ๋ฃ๊ณ , ์ต์๊ฐ์ ๊ฐ์ง ๋
ธ๋ ์ฐพ๊ธฐ
* - ์ต์๊ฐ ๋
ธ๋๋ฅผ ๋๋ฏธ ๋
ธ๋์ ์ฐ๊ฒฐํ ๋ค ์ ๊ฑฐํ๊ณ , ์ต์๊ฐ ๋
ธ๋์ ๋ค์ ๋
ธ๋๋ฅผ ๋ค์ ๋ฐฐ์ด์ ์ถ๊ฐํ๊ธฐ
* - ๋ฐฐ์ด ๊ธธ์ด๊ฐ 0์ด ๋ ๋๊น์ง ๋ฐ๋ณตํ๊ธฐ
*
* ์๊ฐ๋ณต์ก๋ : O(n * k)
* - n = ์ด ๋
ธ๋์ ๊ฐ์
* - k = ๋ฆฌ์คํธ์ ๊ฐ์
* - ์ต์๊ฐ ์ฐพ๊ณ , ์ต์๊ฐ ์ ๊ฑฐํ๋ ๋ก์ง: O(k)
* - ์์ ์ฐ์ฐ์ ์ด n๋ฒ ์คํ
*
* ๊ณต๊ฐ๋ณต์ก๋ : O(k)
* - k = ๋ฆฌ์คํธ ๊ฐ์
* - minList ๋ฐฐ์ด์ ํฌ๊ธฐ๊ฐ ์ต๋ K๊ฐ๊น์ง ์ ์ง
*
*/
function mergeKLists(lists: Array<ListNode | null>): ListNode | null {
const minList: ListNode[] = [];
for (const list of lists) {
if (list !== null) minList.push(list);
}
const dummy = new ListNode();
let tail = dummy;
while (minList.length > 0) {
const minIndex = getMinIndex(minList);
const minNode = minList.splice(minIndex, 1)[0];
tail.next = minNode;
tail = tail.next;
if (minNode.next) minList.push(minNode.next);
}
return dummy.next;
}
function getMinIndex(nodes: ListNode[]): number {
let minIndex = 0;
for (let i = 1; i < nodes.length; i++) {
if (nodes[i].val < nodes[minIndex].val) minIndex = i;
}
return minIndex;
}