Skip to content

Commit f8b4e76

Browse files
committed
add solution: merge-two-sorted-lists
1 parent 9939e5c commit f8b4e76

File tree

1 file changed

+37
-0
lines changed

1 file changed

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

0 commit comments

Comments
ย (0)