Skip to content

Commit 857337b

Browse files
committed
feat: add merge two sorted lists solution
1 parent 33741a7 commit 857337b

File tree

1 file changed

+34
-0
lines changed

1 file changed

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

0 commit comments

Comments
ย (0)