File tree Expand file tree Collapse file tree 1 file changed +38
-0
lines changed Expand file tree Collapse file tree 1 file changed +38
-0
lines changed Original file line number Diff line number Diff line change
1
+ # https://leetcode.com/problems/merge-two-sorted-lists/
2
+
3
+ from typing import Optional
4
+
5
+ # Definition for singly-linked list.
6
+ class ListNode :
7
+ def __init__ (self , val = 0 , next = None ):
8
+ self .val = val
9
+ self .next = next
10
+
11
+ class Solution :
12
+ def mergeTwoLists (self , list1 : Optional [ListNode ], list2 : Optional [ListNode ]) -> Optional [ListNode ]:
13
+ """
14
+ [Complexity]
15
+ - TC: O(n)
16
+ - SC: O(1)
17
+
18
+ [Approach]
19
+ 이미 list1, list2가 non-decreasing order로 정렬되어 있으므로, 각 linked list를 하나씩 비교하며 더 작은 값을 가진 노드부터 모으면 된다.
20
+ 그리고 list1, list2 중에 하나라도 다 본 경우, 남은 linked list를 끝에 붙이면 된다.
21
+ """
22
+ res = curr = ListNode ()
23
+
24
+ while list1 and list2 :
25
+ if list1 .val <= list2 .val :
26
+ curr .next = list1
27
+ list1 = list1 .next
28
+ else :
29
+ curr .next = list2
30
+ list2 = list2 .next
31
+ curr = curr .next
32
+
33
+ if list1 :
34
+ curr .next = list1
35
+ if list2 :
36
+ curr .next = list2
37
+
38
+ return res .next
You can’t perform that action at this time.
0 commit comments