Skip to content

[Lyla] Week 10 #1017

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 4 commits into from
Feb 16, 2025
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
41 changes: 41 additions & 0 deletions course-schedule/pmjuu.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
'''
시간 복잡도: O(V + E)
- 위상 정렬(Topological Sort)을 사용하여 모든 노드(과목)와 간선(선수 과목 관계)을 탐색하므로 O(V + E)입니다.
- V: 노드(과목) 개수 (numCourses)
- E: 간선(선수 과목 관계) 개수 (prerequisites의 길이)

공간 복잡도: O(V + E)
- 그래프를 인접 리스트로 저장하는 데 O(V + E) 공간이 필요합니다.
- 추가적으로 방문 상태를 저장하는 리스트가 필요하여 O(V).
- 따라서 총 공간 복잡도는 O(V + E)입니다.
'''

from collections import deque
from typing import List

class Solution:
def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:
# 그래프 초기화
graph = {i: [] for i in range(numCourses)}
in_degree = {i: 0 for i in range(numCourses)}

# 선수 과목 정보 그래프에 저장
for course, pre in prerequisites:
graph[pre].append(course)
in_degree[course] += 1

# 진입 차수가 0인 과목(선수 과목이 없는 과목)을 큐에 추가
queue = deque([course for course in in_degree if in_degree[course] == 0])
completed_courses = 0

while queue:
current = queue.popleft()
completed_courses += 1

for neighbor in graph[current]:
in_degree[neighbor] -= 1
if in_degree[neighbor] == 0:
queue.append(neighbor)

# 모든 과목을 수강할 수 있다면 True, 아니면 False
return completed_courses == numCourses
21 changes: 21 additions & 0 deletions invert-binary-tree/pmjuu.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
'''
시간복잡도: O(n)
공간복잡도: O(n)
'''
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:
def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
if not root:
return None

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

return root
53 changes: 53 additions & 0 deletions jump-game/pmjuu.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
'''
시간 복잡도: O(n^2)
- 각 인덱스 `i`에서 최대 `nums[i]` 범위만큼의 `step`을 탐색하며, 최악의 경우 O(n)번의 내부 연산이 수행됩니다.

공간 복잡도: O(n)
'''

class Solution:
def canJump(self, nums: List[int]) -> bool:
n = len(nums)
if n == 1:
return True

dp = [False] * n
dp[-2] = (nums[-2] >= 1)

for i in range(n - 3, -1, -1):
num = nums[i]
can_jump_to_end = (num >= n - i - 1)
if can_jump_to_end:
dp[i] = True
continue

can_jump_through_next_index = any([dp[i + step] for step in range(1, min(num + 1, n))])
dp[i] = can_jump_through_next_index

return dp[0]


'''
시간 복잡도: O(n)
- 배열을 한 번만 순회하면서 가장 멀리 도달할 수 있는 위치를 갱신하므로 O(n)입니다.

공간 복잡도: O(1)
'''

from typing import List

class Solution:
def canJump(self, nums: List[int]) -> bool:
max_reach = 0
n = len(nums)

for i in range(n):
if i > max_reach: # 현재 인덱스가 도달 가능한 최대 범위를 넘어선 경우
return False

max_reach = max(max_reach, i + nums[i]) # 도달 가능한 최대 거리 갱신

if max_reach >= n - 1: # 마지막 인덱스에 도달 가능하면 True 반환
return True

return False
34 changes: 34 additions & 0 deletions search-in-rotated-sorted-array/pmjuu.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
'''
시간 복잡도: O(log n)
- 이진 탐색(Binary Search)을 사용하여 배열을 절반씩 나누며 탐색하므로 O(log n)입니다.

공간 복잡도: O(1)
- 추가적인 배열을 사용하지 않고, 몇 개의 변수만 사용하므로 O(1)입니다.
'''

from typing import List

class Solution:
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