Skip to content

Commit

Permalink
feat: add merge two sorted lists solution
Browse files Browse the repository at this point in the history
  • Loading branch information
mangodm-web committed Oct 2, 2024
1 parent 33741a7 commit 857337b
Showing 1 changed file with 34 additions and 0 deletions.
34 changes: 34 additions & 0 deletions merge-two-sorted-lists/mangodm-web.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
from typing import Optional


class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next


class Solution:
def mergeTwoLists(
self, list1: Optional[ListNode], list2: Optional[ListNode]
) -> Optional[ListNode]:
"""
- Idea: dummy node๋ฅผ ํ•˜๋‚˜ ๋งŒ๋“ค๊ณ , ๋‘ ๋ฆฌ์ŠคํŠธ๋ฅผ ์ˆœํšŒํ•˜๋ฉด์„œ ๊ฐ’์„ ๋น„๊ตํ•˜์—ฌ ๋” ์ž‘์€ ๋…ธ๋“œ๋ฅผ dummy node์— ์ด์–ด ๋ถ™์ธ๋‹ค.
๋‘˜ ์ค‘ ํ•˜๋‚˜๊ฐ€ ๋จผ์ € ์ˆœํšŒ๊ฐ€ ๋๋‚ฌ๋‹ค๋ฉด, ๋‚˜๋จธ์ง€ ๋ฆฌ์ŠคํŠธ์˜ ๋‚จ์€ ๋…ธ๋“œ๋“ค์„ ๊ทธ๋Œ€๋กœ ์ด์–ด ๋ถ™์ธ๋‹ค. (๋ฆฌ์ŠคํŠธ ๋‚ด์—์„œ๋Š” ์ˆœ์„œ๊ฐ€ ์ •๋ ฌ๋˜์–ด ์žˆ์Œ์ด ๋ณด์žฅ๋˜์–ด ์žˆ๊ธฐ ๋•Œ๋ฌธ์— ๊ฐ€๋Šฅํ•˜๋‹ค.)
- Time Complexity: O(n), n์€ m + k, m๊ณผ k์€ ๊ฐ๊ฐ list1, list2์˜ ๊ธธ์ด์ด๋‹ค.
- Space Complexity: O(1), ์ถ”๊ฐ€์ ์ธ ๊ณต๊ฐ„์€ ์‚ฌ์šฉํ•˜์ง€ ์•Š๊ณ , ๊ธฐ์กด ๋…ธ๋“œ๋ฅผ ์žฌ์‚ฌ์šฉํ•˜์—ฌ ์—ฐ๊ฒฐํ•œ๋‹ค.
"""
merged = ListNode()
cur = merged

while list1 and list2:
if list1.val > list2.val:
cur.next = list2
list2 = list2.next
else:
cur.next = list1
list1 = list1.next
cur = cur.next

cur.next = list1 or list2

return merged.next

0 comments on commit 857337b

Please sign in to comment.