Skip to content

Commit 7d53495

Browse files
committed
Solved "Merge Two Sorted Lists"
1 parent 502ea89 commit 7d53495

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
@@ -1 +1,45 @@
1+
"""
2+
Constraints:
3+
1. 0 <= list1.length, list2.length <= 50
4+
2. -100 <= Node.val <= 100
5+
3. list1 and list2 are sorted in non-decreasing order
16
7+
Time Complexity: n๊ณผ m์ด ๊ฐ๊ฐ list1๊ณผ list2์˜ ๊ธธ์ด๋ฅผ ๋‚˜ํƒ€๋‚ผ ๋•Œ, O(n + m)
8+
- ๊ฐ ๋…ธ๋“œ๋ฅผ ํ•œ ๋ฒˆ์”ฉ๋งŒ ๋ฐฉ๋ฌธํ•˜๊ธฐ ๋•Œ๋ฌธ
9+
10+
Space Complexity: O(1)
11+
- ์ƒˆ๋กœ์šด ๋…ธ๋“œ๋ฅผ ๋งŒ๋“ค์ง€ ์•Š๊ณ  ๊ธฐ์กด ๋…ธ๋“œ๋“ค์˜ ์—ฐ๊ฒฐ๋งŒ ๋ฐ”๊พธ๊ธฐ ๋•Œ๋ฌธ
12+
13+
ํ’€์ด ๋ฐฉ๋ฒ•:
14+
1. ๋”๋ฏธ ๋…ธ๋“œ๋ฅผ ๋งŒ๋“ค์–ด์„œ ๊ฒฐ๊ณผ ๋ฆฌ์ŠคํŠธ์˜ ์‹œ์ž‘์ ์œผ๋กœ ์‚ฌ์šฉ
15+
2. ๋‘ ๋ฆฌ์ŠคํŠธ๋ฅผ ์•ž์—์„œ๋ถ€ํ„ฐ ์ˆœํšŒํ•˜๋ฉด์„œ ๊ฐ’์„ ๋น„๊ต
16+
3. ๋” ์ž‘์€ ๊ฐ’์„ ๊ฐ€์ง„ ๋…ธ๋“œ๋ฅผ ๊ฒฐ๊ณผ ๋ฆฌ์ŠคํŠธ์— ์—ฐ๊ฒฐํ•˜๊ณ , ํ•ด๋‹น ๋ฆฌ์ŠคํŠธ์˜ ํฌ์ธํ„ฐ๋ฅผ ๋‹ค์Œ์œผ๋กœ ์ด๋™
17+
4. ํ•œ์ชฝ ๋ฆฌ์ŠคํŠธ๊ฐ€ ๋๋‚˜๋ฉด, ๋‚จ์€ ๋ฆฌ์ŠคํŠธ๋ฅผ ๊ทธ๋Œ€๋กœ ๊ฒฐ๊ณผ ๋ฆฌ์ŠคํŠธ ๋’ค์— ์—ฐ๊ฒฐ
18+
5. ๋”๋ฏธ ๋…ธ๋“œ์˜ next๋ฅผ ๋ฐ˜ํ™˜ (์‹ค์ œ ์ •๋ ฌ๋œ ๋ฆฌ์ŠคํŠธ์˜ ์‹œ์ž‘์ )
19+
"""
20+
21+
# Definition for singly-linked list.
22+
# class ListNode:
23+
# def __init__(self, val=0, next=None):
24+
# self.val = val
25+
# self.next = next
26+
class Solution:
27+
def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
28+
result = ListNode()
29+
current = result
30+
31+
while list1 and list2:
32+
if list1.val <= list2.val:
33+
current.next = list1
34+
list1 = list1.next
35+
else:
36+
current.next = list2
37+
list2 = list2.next
38+
current = current.next
39+
40+
if list1:
41+
current.next = list1
42+
if list2:
43+
current.next = list2
44+
45+
return result.next

0 commit comments

Comments
ย (0)