Skip to content

Commit e488dfb

Browse files
committed
feat: Add Merge Two Sorted Lists solutions
1 parent 25f4d4c commit e488dfb

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
# Definition for singly-linked list.
2+
# class ListNode:
3+
# def __init__(self, val=0, next=None):
4+
# self.val = val
5+
# self.next = next
6+
class Solution:
7+
def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
8+
"""
9+
Intuition:
10+
๋‘ ๋ฆฌ์ŠคํŠธ์˜ ์›์†Œ๋ฅผ ๊ฐ๊ฐ ๋น„๊ตํ•˜๋ฉด์„œ ํ•œ๋ฒˆ์”ฉ ์Šค์บ”ํ•œ๋‹ค.
11+
๊ฒฐ๊ณผ์ ์œผ๋กœ ํ•œ๋ฒˆ์”ฉ๋งŒ ์Šค์บ”ํ•˜๋ฉด ์ •๋ ฌํ•  ์ˆ˜ ์žˆ๋‹ค.
12+
13+
Time Complexity:
14+
O(N):
15+
๋‘๊ฐœ์˜ ๋ฆฌ์ŠคํŠธ๋ฅผ 1๋ฒˆ ์ˆœํšŒํ•˜๋ฉฐ ๋‹ต์„ ์ฐพ์œผ๋ฏ€๋กœ,
16+
O(N)์˜ ์‹œ๊ฐ„๋ณต์žก๋„๊ฐ€ ์†Œ์š”๋œ๋‹ค.
17+
18+
Space Complexity:
19+
O(N):
20+
sorted_list์— ์ •๋ ฌ๋œ ๋ฐฐ์—ด์„ ์ €์žฅํ•˜๋ฏ€๋กœ,
21+
O(N)์˜ ๊ณต๊ฐ„๋ณต์žก๋„๊ฐ€ ์†Œ์š”๋œ๋‹ค.
22+
"""
23+
sorted_list = []
24+
while list1 is not None and list2 is not None:
25+
if list1.val < list2.val:
26+
sorted_list.append(list1.val)
27+
list1 = list1.next
28+
else:
29+
sorted_list.append(list2.val)
30+
list2 = list2.next
31+
32+
while list1 is not None:
33+
sorted_list.append(list1.val)
34+
list1 = list1.next
35+
while list2 is not None:
36+
sorted_list.append(list2.val)
37+
list2 = list2.next
38+
39+
sorted_node = None
40+
while sorted_list:
41+
val = sorted_list.pop()
42+
sorted_node = ListNode(val, sorted_node)
43+
44+
return sorted_node

0 commit comments

Comments
ย (0)