-
-
Notifications
You must be signed in to change notification settings - Fork 195
[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
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
e2c140b
feat: add invert binary tree solution
mangodm-web 5746266
feat: add search in rotated sorted array solution
mangodm-web dadf405
feat: add course schedule solution
mangodm-web 8b0a302
fix: update invert binary tree solution comment
mangodm-web 4448abc
fix: update course schedule solution comment
mangodm-web File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or 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,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 |
This file contains hidden or 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,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 |
This file contains hidden or 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 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 | ||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
이분탐색에서 제일 귀찮은게 어디에 등호 넣고 어디에 +1 아니면 -1 하느냐인데, 다른 문제에서 아 이거 이분탐색이다 싶을 때, 각각 조절해보시면 좋을 것 같습니다. 어떨 때는 되고 어떨 때는 안되어서 골치아플 때가 있습니다.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@lymchgmk님,
범위를 조정하는 부분이 정말 까다롭더라구요. 앞으로는 문제 풀 때, 이 부분을 좀 더 신경 써봐야겠네요.
좋은 팁 감사합니다!