-
Notifications
You must be signed in to change notification settings - Fork 126
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: add merge two sorted lists solution
- Loading branch information
1 parent
33741a7
commit 857337b
Showing
1 changed file
with
34 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |