Skip to content

Commit f6c49e9

Browse files
authored
Merge pull request #1038 from pmjuu/main
[Lyla] Week 11
2 parents c60aadd + d7f9e15 commit f6c49e9

File tree

3 files changed

+87
-0
lines changed

3 files changed

+87
-0
lines changed

maximum-depth-of-binary-tree/pmjuu.py

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
'''
2+
시간 복잡도: O(n)
3+
공간 복잡도: O(n)
4+
'''
5+
from typing import Optional
6+
7+
# Definition for a binary tree node.
8+
class TreeNode:
9+
def __init__(self, val=0, left=None, right=None):
10+
self.val = val
11+
self.left = left
12+
self.right = right
13+
14+
class Solution:
15+
def maxDepth(self, root: Optional[TreeNode]) -> int:
16+
if not root:
17+
return 0
18+
19+
left = self.maxDepth(root.left)
20+
right = self.maxDepth(root.right)
21+
22+
return max(left, right) + 1

merge-intervals/pmjuu.py

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
'''
2+
시간 복잡도: O(n log n)
3+
- intervals 정렬하는 데 O(n log n)
4+
- intervals 한 번 순회하면서 병합 작업 수행: O(n)
5+
6+
공간 복잡도: O(n)
7+
- 결과 리스트에 병합된 interval을 저장해야 하므로 O(n)
8+
'''
9+
from typing import List
10+
11+
class Solution:
12+
def merge(self, intervals: List[List[int]]) -> List[List[int]]:
13+
result = []
14+
intervals.sort(key=lambda x: x[0])
15+
left, right = intervals[0]
16+
17+
for start, end in intervals[1:]:
18+
# stop merging
19+
if 0 <= right < start:
20+
result.append([left, right])
21+
left, right = start, end
22+
# merge overlapping intervals
23+
else:
24+
left, right = min(left, start), max(right, end)
25+
26+
result.append([left, right])
27+
28+
return result

reorder-list/pmjuu.py

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
'''
2+
시간 복잡도: O(n)
3+
- 중간 노드 찾기: O(n)
4+
- 리스트 반전: O(n)
5+
- 리스트 병합: O(n)
6+
7+
공간 복잡도: O(1)
8+
- 포인터만 사용하여 링크를 조작하므로 O(1)
9+
'''
10+
from typing import Optional
11+
# Definition for singly-linked list.
12+
class ListNode:
13+
def __init__(self, val=0, next=None):
14+
self.val = val
15+
self.next = next
16+
17+
class Solution:
18+
def reorderList(self, head: Optional[ListNode]) -> None:
19+
"""
20+
Do not return anything, modify head in-place instead.
21+
"""
22+
# find the middle node
23+
slow, fast = head, head
24+
while fast and fast.next:
25+
slow = slow.next
26+
fast = fast.next.next
27+
28+
# reverse back half of the list
29+
prev, curr = None, slow.next
30+
slow.next = None # cut in the middle
31+
while curr:
32+
curr.next, prev, curr = prev, curr, curr.next
33+
34+
# merge front half with back half
35+
first, second = head, prev
36+
while second:
37+
first.next, second.next, first, second = second, first.next, first.next, second.next

0 commit comments

Comments
 (0)