File tree Expand file tree Collapse file tree 1 file changed +34
-0
lines changed Expand file tree Collapse file tree 1 file changed +34
-0
lines changed Original file line number Diff line number Diff line change 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
You canโt perform that action at this time.
0 commit comments