Skip to content

Commit 64e2fe6

Browse files
committed
add solution : 21. Merge Two Sorted Lists
1 parent 9b45bea commit 64e2fe6

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

โ€Žmerge-two-sorted-lists/mmyeon.ts

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
class ListNode {
2+
val: number;
3+
next: ListNode | null;
4+
constructor(val?: number, next?: ListNode | null) {
5+
this.val = val === undefined ? 0 : val;
6+
this.next = next === undefined ? null : next;
7+
}
8+
}
9+
10+
/**
11+
*
12+
* ์ ‘๊ทผ ๋ฐฉ๋ฒ• :
13+
* - 2๊ฐœ์˜ ์ •๋ ฌ๋œ ๋งํฌ๋“œ ๋ฆฌ์ŠคํŠธ๊ฐ€ ์ฃผ์–ด์ง€๋‹ˆ๊นŒ ๊ฐ ๋ฆฌ์ŠคํŠธ ๊ฐ’ ๋น„๊ตํ•˜๋ฉด์„œ ์ž‘์€ ๊ฐ’์„ ์ƒˆ๋กœ์šด ๋งํฌ๋“œ ๋ฆฌ์ŠคํŠธ์— ์ถ”๊ฐ€
14+
* - ๋งํฌ๋“œ ๋ฆฌ์ŠคํŠธ head์— ์ ‘๊ทผํ•ด์•ผํ•˜๋‹ˆ๊นŒ ๋”๋ฏธ๋…ธ๋“œ์™€ ํฌ์ธํ„ฐ ๋ณ€์ˆ˜ ๋ถ„๋ฆฌํ•ด์„œ ์‚ฌ์šฉ
15+
* - ํฌ์ธํ„ฐ ๋ณ€์ˆ˜ ์‚ฌ์šฉํ•ด์„œ ๋…ธ๋“œ ์—ฐ๊ฒฐํ•˜๊ธฐ
16+
* - ๋‘ ๋งํฌ๋“œ ๋ฆฌ์ŠคํŠธ๊ฐ€ ์žˆ๋Š” ๋™์•ˆ ๋ฐ˜๋ณตํ•˜๊ณ , ํ•œ ์ชฝ์ด ๋๋‚˜๋ฉด ๋‚˜๋จธ์ง€ ๋…ธ๋“œ๋ฅผ ๊ทธ๋Œ€๋กœ ์ƒˆ๋กœ์šด ๋งํฌ๋“œ ๋ฆฌ์ŠคํŠธ์— ์ถ”๊ฐ€
17+
*
18+
* ์‹œ๊ฐ„๋ณต์žก๋„ : O(n+k)
19+
* - n์€ list1 ๊ธธ์ด, k๋Š” list2 ๊ธธ์ด => ๋‘ ๋ฆฌ์ŠคํŠธ ๋ชจ๋‘ ๋ฐ˜๋ณตํ•˜๋‹ˆ๊นŒ O(n+k)
20+
*
21+
* ๊ณต๊ฐ„๋ณต์žก๋„ : O(1)
22+
* - ๊ธฐ์กด ๋…ธ๋“œ ์—ฐ๊ฒฐํ•ด์„œ ์žฌ์‚ฌ์šฉํ•˜๋‹ˆ๊นŒ O(1)
23+
*/
24+
25+
function mergeTwoLists(
26+
list1: ListNode | null,
27+
list2: ListNode | null
28+
): ListNode | null {
29+
const dummyNode = new ListNode();
30+
let current = dummyNode;
31+
32+
while (list1 !== null && list2 !== null) {
33+
if (list1.val <= list2.val) {
34+
current.next = list1;
35+
list1 = list1.next;
36+
current = current.next;
37+
} else {
38+
current.next = list2;
39+
list2 = list2.next;
40+
current = current.next;
41+
}
42+
}
43+
current.next = list1 !== null ? list1 : list2;
44+
45+
return dummyNode.next;
46+
}

0 commit comments

Comments
ย (0)