-
-
Notifications
You must be signed in to change notification settings - Fork 360
[alphaorderly] WEEK 13 Solutions #2861
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
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🏷️ 알고리즘 패턴 분석find-median-from-data-stream/alphaorderly.py"""
시간 복잡도: O(LogN)
공간 복잡도: O(N)
최소 힙에는 스트림의 중간값보다 크거나 같은 값들이 저장됨
최대 힙에는 스트림의 중간값보다 작은 값들이 저장됨
두 힙의 경계에 위치한 값을 이용해 중간값을 구한다
"""
class MedianFinder:
def __init__(self):
self.min = []
self.max = []
def addNum(self, num: int) -> None:
heapq.heappush_max(self.max, num)
heapq.heappush(self.min, heapq.heappop_max(self.max))
if len(self.min) > len(self.max):
heapq.heappush_max(self.max, heapq.heappop(self.min))
def findMedian(self) -> float:
if len(self.max) == len(self.min):
return (self.min[0] + self.max[0]) / 2
else:
return self.max[0]
📊 시간/공간 복잡도 분석
풀이 1:
|
| 복잡도 | |
|---|---|
| Time | O(log N) |
| Space | O(N) |
피드백: 최솟값 큐와 최댓값 큐를 이용해 중간값을 빠르게 받아오도록 구현되어 있다.
개선 제안: 현재 구현은 간단하지만 Max Heap/Min Heap의 상호 변환 로직이 직관적이지 않으므로 명확한 주석과 함께 두 힙의 역할을 분리하면 가독성이 높아진다.
풀이 2: MeetingCanAttend.canAttendMeetings — Time: O(N log N) / Space: O(N)
| 복잡도 | |
|---|---|
| Time | O(N log N) |
| Space | O(N) |
피드백: 정렬으로 인해 시간 복잡도는 O(N log N)이고, 순차 검사로 겹침 여부를 판정한다.
개선 제안: 최소 공간에서 동작하도록 정렬을 inplace로 유지하고, 시작/종료를 분리 리스트로 처리하는 방법도 고려해볼 수 있다.
💡 풀이에 시간/공간 복잡도를 주석으로 남겨보세요!
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,27 @@ | ||
| """ | ||
| 시간 복잡도: O(LogN) | ||
| 공간 복잡도: O(N) | ||
|
|
||
| 최소 힙에는 스트림의 중간값보다 크거나 같은 값들이 저장됨 | ||
| 최대 힙에는 스트림의 중간값보다 작은 값들이 저장됨 | ||
|
|
||
| 두 힙의 경계에 위치한 값을 이용해 중간값을 구한다 | ||
| """ | ||
| class MedianFinder: | ||
|
|
||
| def __init__(self): | ||
| self.min = [] | ||
| self.max = [] | ||
|
|
||
| def addNum(self, num: int) -> None: | ||
| heapq.heappush_max(self.max, num) | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 오,
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 3.14에서 추가되었더라구요!! |
||
| heapq.heappush(self.min, heapq.heappop_max(self.max)) | ||
|
|
||
| if len(self.min) > len(self.max): | ||
| heapq.heappush_max(self.max, heapq.heappop(self.min)) | ||
|
|
||
| def findMedian(self) -> float: | ||
| if len(self.max) == len(self.min): | ||
| return (self.min[0] + self.max[0]) / 2 | ||
| else: | ||
| return self.max[0] | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🏷️ 알고리즘 패턴 분석insert-interval/alphaorderly.py"""
시간 복잡도: O(N)
공간 복잡도: O(N)
- 새로운 배열을 만들어 리턴하기 떄문이다.
기존 intervals 리스트에 새 interval을 삽입하여 겹치는 구간을 병합하는 코드입니다.
intervals는 이미 정렬되어 있다고 가정하며,
새로운 interval과의 겹침 여부를 판별하여 겹치면 병합하고, 그렇지 않으면 적절한 위치에 삽입합니다.
"""
class Solution:
def insert(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]:
ans = []
added = False
for start, end in intervals:
if added:
ans.append([start, end])
continue
if end < newInterval[0]:
ans.append([start, end])
elif start > newInterval[1]:
ans.append(newInterval)
ans.append([start, end])
added = True
else:
newInterval = [min(start, newInterval[0]), max(newInterval[1], end)]
if not added:
ans.append(newInterval)
return ans
📊 시간/공간 복잡도 분석
피드백: 주어진 입력이 이미 정렬되어 있다는 가정하에 단일 순회로 병합/삽입을 수행한다. 개선 제안: 현재 구현이 적절해 보입니다.
|
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,32 @@ | ||
| """ | ||
| 시간 복잡도: O(N) | ||
| 공간 복잡도: O(N) | ||
| - 새로운 배열을 만들어 리턴하기 떄문이다. | ||
|
|
||
| 기존 intervals 리스트에 새 interval을 삽입하여 겹치는 구간을 병합하는 코드입니다. | ||
| intervals는 이미 정렬되어 있다고 가정하며, | ||
| 새로운 interval과의 겹침 여부를 판별하여 겹치면 병합하고, 그렇지 않으면 적절한 위치에 삽입합니다. | ||
| """ | ||
| class Solution: | ||
| def insert(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]: | ||
| ans = [] | ||
| added = False | ||
|
|
||
| for start, end in intervals: | ||
| if added: | ||
| ans.append([start, end]) | ||
| continue | ||
|
|
||
| if end < newInterval[0]: | ||
| ans.append([start, end]) | ||
| elif start > newInterval[1]: | ||
| ans.append(newInterval) | ||
| ans.append([start, end]) | ||
| added = True | ||
| else: | ||
| newInterval = [min(start, newInterval[0]), max(newInterval[1], end)] | ||
|
|
||
| if not added: | ||
| ans.append(newInterval) | ||
|
|
||
| return ans |
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🏷️ 알고리즘 패턴 분석kth-smallest-element-in-a-bst/alphaorderly.py"""
시간 복잡도: O(N)
공간 복잡도: O(N)
이 코드는 이진 탐색 트리(BST)에서 k번째로 작은 값을 찾는 함수입니다.
중위 순회를 통해 노드를 오름차순으로 방문하여,
k번째 값을 찾는 방식으로 동작합니다.
"""
class Solution:
def kthSmallest(self, root: Optional[TreeNode], k: int) -> int:
stack = []
index = 1
while root:
stack.append(root)
root = root.left
while stack:
node = stack.pop()
if index == k:
return node.val
index += 1
if not node.right:
continue
right = node.right
while right:
stack.append(right)
right = right.left
return -1
📊 시간/공간 복잡도 분석
피드백: 스택을 사용한 반복적 중위 순회로 순서를 따라간다. 개선 제안: 현재 구현이 적절해 보입니다.
|
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,33 @@ | ||
| """ | ||
| 시간 복잡도: O(N) | ||
| 공간 복잡도: O(N) | ||
|
|
||
| 이 코드는 이진 탐색 트리(BST)에서 k번째로 작은 값을 찾는 함수입니다. | ||
| 중위 순회를 통해 노드를 오름차순으로 방문하여, | ||
| k번째 값을 찾는 방식으로 동작합니다. | ||
| """ | ||
| class Solution: | ||
| def kthSmallest(self, root: Optional[TreeNode], k: int) -> int: | ||
| stack = [] | ||
| index = 1 | ||
|
|
||
| while root: | ||
| stack.append(root) | ||
| root = root.left | ||
|
|
||
| while stack: | ||
| node = stack.pop() | ||
|
|
||
| if index == k: | ||
| return node.val | ||
| index += 1 | ||
|
|
||
| if not node.right: | ||
| continue | ||
|
Comment on lines
+25
to
+26
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 아래
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 맞네요!! |
||
|
|
||
| right = node.right | ||
| while right: | ||
| stack.append(right) | ||
| right = right.left | ||
|
|
||
| return -1 | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🏷️ 알고리즘 패턴 분석lowest-common-ancestor-of-a-binary-search-tree/alphaorderly.py"""
시간 복잡도: O(N)
공간 복잡도: O(N)
BST에서 두 노드의 최소 공통 조상을 찾는 코드입니다.
두 노드의 값을 비교하여 최소 공통 조상을 찾는 방식으로 동작합니다.
"""
class Solution:
def lowestCommonAncestor(
self, root: "TreeNode", p: "TreeNode", q: "TreeNode"
) -> "TreeNode":
if root == p or root == q:
return root
p_compare = root.val > p.val
q_compare = root.val > q.val
if p_compare != q_compare:
return root
elif p_compare and q_compare:
return self.lowestCommonAncestor(root.left, p, q)
else:
return self.lowestCommonAncestor(root.right, p, q)
📊 시간/공간 복잡도 분석
피드백: 루트에서 값을 비교해 적절한 분기에서 재귀적으로 해결한다. 개선 제안: 현재 구현이 적절해 보입니다.
|
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,23 @@ | ||
| """ | ||
| 시간 복잡도: O(N) | ||
| 공간 복잡도: O(N) | ||
|
|
||
| BST에서 두 노드의 최소 공통 조상을 찾는 코드입니다. | ||
| 두 노드의 값을 비교하여 최소 공통 조상을 찾는 방식으로 동작합니다. | ||
| """ | ||
| class Solution: | ||
| def lowestCommonAncestor( | ||
| self, root: "TreeNode", p: "TreeNode", q: "TreeNode" | ||
| ) -> "TreeNode": | ||
| if root == p or root == q: | ||
| return root | ||
|
|
||
| p_compare = root.val > p.val | ||
| q_compare = root.val > q.val | ||
|
|
||
| if p_compare != q_compare: | ||
| return root | ||
| elif p_compare and q_compare: | ||
| return self.lowestCommonAncestor(root.left, p, q) | ||
| else: | ||
| return self.lowestCommonAncestor(root.right, p, q) |
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🏷️ 알고리즘 패턴 분석meeting-rooms/alphaorderly.py"""
시간 복잡도: O(NLogN)
- intervals 리스트를 정렬하기 때문입니다.
공간 복잡도: O(N)
- 정렬 시 추가 메모리(새로운 배열)가 사용될 수 있습니다.
주어진 intervals(회의 시간표)들이 서로 겹치는지 확인하는 코드입니다.
intervals를 시작 시간 순으로 정렬한 뒤,
이전 회의의 종료 시간(final)과 현재 회의의 시작 시간(start)을 비교하여
회의가 겹치는 경우가 있는지 검사합니다.
"""
class Solution:
def canAttendMeetings(self, intervals: List[List[int]]) -> bool:
intervals.sort()
final = -1
for start, end in intervals:
if start >= final:
final = end
else:
return False
return True
📊 시간/공간 복잡도 분석
피드백: 정렬 비용으로 인해 전체 시간복잡도가 증가한다. 개선 제안: 현재 구현이 적절해 보입니다.
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🏷️ 알고리즘 패턴 분석meeting-rooms/alphaorderly.py"""
시간 복잡도: O(NLogN)
- intervals 리스트를 정렬하기 때문입니다.
공간 복잡도: O(N)
- 정렬 시 추가 메모리(새로운 배열)가 사용될 수 있습니다.
주어진 intervals(회의 시간표)들이 서로 겹치는지 확인하는 코드입니다.
intervals를 시작 시간 순으로 정렬한 뒤,
이전 회의의 종료 시간(final)과 현재 회의의 시작 시간(start)을 비교하여
회의가 겹치는 경우가 있는지 검사합니다.
"""
class Solution:
def canAttendMeetings(self, intervals: List[List[int]]) -> bool:
intervals.sort()
final = -1
for start, end in intervals:
if start >= final:
final = end
else:
return False
return True
|
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,23 @@ | ||
| """ | ||
| 시간 복잡도: O(NLogN) | ||
| - intervals 리스트를 정렬하기 때문입니다. | ||
| 공간 복잡도: O(N) | ||
| - 정렬 시 추가 메모리(새로운 배열)가 사용될 수 있습니다. | ||
|
|
||
| 주어진 intervals(회의 시간표)들이 서로 겹치는지 확인하는 코드입니다. | ||
| intervals를 시작 시간 순으로 정렬한 뒤, | ||
| 이전 회의의 종료 시간(final)과 현재 회의의 시작 시간(start)을 비교하여 | ||
| 회의가 겹치는 경우가 있는지 검사합니다. | ||
| """ | ||
| class Solution: | ||
| def canAttendMeetings(self, intervals: List[List[int]]) -> bool: | ||
| intervals.sort() | ||
| final = -1 | ||
|
|
||
| for start, end in intervals: | ||
| if start >= final: | ||
| final = end | ||
| else: | ||
| return False | ||
|
|
||
| return True |
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.
🏷️ 알고리즘 패턴 분석
find-median-from-data-stream/alphaorderly.py
📊 시간/공간 복잡도 분석
피드백: 최대 힙과 최소 힙을 이용해 중앙값 경계를 유지하고 필요 시 재조정한다.
개선 제안: 현재 구현이 적절해 보입니다.