Skip to content

Commit 365c8e4

Browse files
committed
Merge Two Sorted Listsํ’€์ด
1 parent 892bb03 commit 365c8e4

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
"""
2+
๋ฌธ์ œ ์š”์•ฝ
3+
- ์ •๋ ฌ๋œ ๋‘ ์—ฐ๊ฒฐ ๋ฆฌ์ŠคํŠธ๋ฅผ ํ•˜๋‚˜์˜ ์ •๋ ฌ๋œ ๋ฆฌ์ŠคํŠธ๋กœ ๋ณ‘ํ•ฉ
4+
5+
์•„์ด๋””์–ด
6+
- dummy ๋…ธ๋“œ๋กœ ์‹œ์ž‘์  ๊ณ ์ •
7+
- ๋‘ ๋ฆฌ์ŠคํŠธ ๋น„๊ตํ•˜๋ฉฐ ์ž‘์€ ๊ฐ’์„ ์—ฐ๊ฒฐ
8+
- ๋‚จ์€ ๋ฆฌ์ŠคํŠธ ํ•œ๋ฒˆ์— ์—ฐ๊ฒฐ
9+
10+
์‹œ๊ฐ„๋ณต์žก๋„: O(n + m) - ๋‘ ๋ฆฌ์ŠคํŠธ ๊ธธ์ด์˜ ํ•ฉ
11+
๊ณต๊ฐ„๋ณต์žก๋„: O(1) - ์ถ”๊ฐ€ ๊ณต๊ฐ„ ์—†์ด ํฌ์ธํ„ฐ๋งŒ ๋ณ€๊ฒฝ
12+
"""
13+
14+
15+
class Solution:
16+
def mergeTwoLists(
17+
self, list1: Optional[ListNode], list2: Optional[ListNode]
18+
) -> Optional[ListNode]:
19+
dummy = ListNode() # ๊ฐ€์งœ ์‹œ์ž‘ ๋…ธ๋“œ
20+
node = dummy
21+
22+
# ๋‘ ๋ฆฌ์ŠคํŠธ ๋น„๊ตํ•˜๋ฉฐ ๋ณ‘ํ•ฉ
23+
while list1 and list2:
24+
if list1.val < list2.val:
25+
node.next = list1
26+
list1 = list1.next
27+
else:
28+
node.next = list2
29+
list2 = list2.next
30+
node = node.next
31+
32+
# ๋‚จ์€ ๋ฆฌ์ŠคํŠธ ์—ฐ๊ฒฐ
33+
node.next = list1 or list2
34+
35+
return dummy.next

0 commit comments

Comments
ย (0)