Skip to content

[mangodm-web] Week10 Solutions #543

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Oct 21, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 43 additions & 0 deletions course-schedule/mangodm-web.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
from typing import List


class Solution:
def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:
"""
- Idea: 각 과목의 선행 과목에 사이클이 존재하는지 DFS로 탐색한다.
하나라도 사이클이 존재한다면, 모든 과목을 수강할 수 없다는 의미다.
- Time Complexity: O(v + e). v와 e는 각각 과목의 수, e는 선행 관계(과목 => 선행 과목)의 수다.
모든 과목과 그 과목의 선행 과목을 탐색해야 하기 때문에 각 노드와 엣지에 대해 한번씩 방문해야 한다.
- Space Complexity: O(v + e). v와 e는 각각 과목의 수, e는 선행 관계의 수다.
각 과목의 방문 여부를 기록하기 위해 O(v) 공간이 필요하고,
과목 간 선행 관계를 저장하는 인접 리스트는 O(e)의 공간을 차지한다.
"""

graph = {i: [] for i in range(numCourses)}

for course, prerequisite in prerequisites:
graph[course].append(prerequisite)

visited = set()

def DFS(course):
if course in visited:
return False
if graph[course] == []:
return True

visited.add(course)
for prerequisite in graph[course]:
if not DFS(prerequisite):
return False

visited.remove(course)
graph[course] = []

return True

for course in range(numCourses):
if not DFS(course):
return False

return True
29 changes: 29 additions & 0 deletions invert-binary-tree/mangodm-web.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
from typing import Optional


class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right


class Solution:
"""
- Idea: 재귀를 이용하여 각 노드의 왼쪽 자식과 오른쪽 자식을 바꾼다.
- Time Complexity: O(n). n은 전체 노드의 수다.
모든 노드에 대해서 반복적으로 수행해야 하기 때문에 O(n) 시간이 걸린다.
- Space Complexity: O(n). n은 전체 노드의 수다.
최악의 경우, 불균형 트리에서는 재귀 호출로 인해 최대 O(n) 스택 공간이 필요하다.
"""

def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
if root is None:
return

root.left, root.right = root.right, root.left

self.invertTree(root.left)
self.invertTree(root.right)

return root
34 changes: 34 additions & 0 deletions search-in-rotated-sorted-array/mangodm-web.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
from typing import List


class Solution:
"""
- 아이디어: 배열의 중간 값을 기준으로 왼쪽, 오른쪽 중 한쪽은 항상 정렬되어 있다.
이 특징에 착안하여, 어느 쪽이 먼저 정렬되어 있는지 확인하고, 그 안에
찾으려는 값이 있는지를 확인하는 방식으로 탐색 범위를 좁혀간다.
- 시간 복잡도: O(logn). n은 배열의 길이.
배열을 절반씩 나누어 탐색을 진행하기 때문에 시간 복잡도는 O(logn)이다.
- 공간 복잡도: O(1). 추가적인 메모리를 사용하지 않고, 상수 공간만 필요하다.
"""

def search(self, nums: List[int], target: int) -> int:
left, right = 0, len(nums) - 1

while left <= right:
mid = (left + right) // 2

if nums[mid] == target:
return mid

if nums[left] <= nums[mid]:
if nums[left] <= target < nums[mid]:
right = mid - 1
else:
left = mid + 1
else:
if nums[mid] < target <= nums[right]:
left = mid + 1
else:
right = mid - 1

return -1
Comment on lines +17 to +34
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

이분탐색에서 제일 귀찮은게 어디에 등호 넣고 어디에 +1 아니면 -1 하느냐인데, 다른 문제에서 아 이거 이분탐색이다 싶을 때, 각각 조절해보시면 좋을 것 같습니다. 어떨 때는 되고 어떨 때는 안되어서 골치아플 때가 있습니다.

Copy link
Contributor Author

@mangodm-web mangodm-web Oct 21, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@lymchgmk님,
범위를 조정하는 부분이 정말 까다롭더라구요. 앞으로는 문제 풀 때, 이 부분을 좀 더 신경 써봐야겠네요.
좋은 팁 감사합니다!