Repository navigation
[parkhojeong] WEEK 14 Solutions #2870
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
Changes from all commits
4e17b5f
c3d0211
b1d6e14
b57c83f
18c9bdd
c38eacc
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. 🏷️ 알고리즘 패턴 분석binary-tree-level-order-traversal/parkhojeong.py# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def levelOrder(self, root: TreeNode | None) -> list[list[int]]:
if root is None:
return []
deq = deque([root])
output = []
while deq:
nodes = []
for _ in range(len(deq)):
node = deq.popleft()
nodes.append(node.val)
if node.left:
deq.append(node.left)
if node.right:
deq.append(node.right)
output.append(nodes)
return output
📊 시간/공간 복잡도 분석
피드백: 큐를 이용해 BFS로 각 레벨의 노드를 처리하며, 현재 레벨의 노드들만 모아 출력 리스트에 추가한다. 개선 제안: 현재 구현이 적절해 보입니다.
|
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,28 @@ | ||
| # Definition for a binary tree node. | ||
| # class TreeNode: | ||
| # def __init__(self, val=0, left=None, right=None): | ||
| # self.val = val | ||
| # self.left = left | ||
| # self.right = right | ||
| class Solution: | ||
| def levelOrder(self, root: TreeNode | None) -> list[list[int]]: | ||
| if root is None: | ||
| return [] | ||
|
|
||
| deq = deque([root]) | ||
|
|
||
|
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. deque의 경우 deque([root]) 처럼 리스트를 제공해서 바로 초기화가 가능하세요!
Collaborator
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. 오 몰랐네요~ 감사합니다! |
||
| output = [] | ||
| while deq: | ||
| nodes = [] | ||
|
|
||
| for _ in range(len(deq)): | ||
| node = deq.popleft() | ||
| nodes.append(node.val) | ||
| if node.left: | ||
| deq.append(node.left) | ||
| if node.right: | ||
| deq.append(node.right) | ||
|
|
||
| output.append(nodes) | ||
|
|
||
| return output | ||
|
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. 🏷️ 알고리즘 패턴 분석counting-bits/parkhojeong.pyclass Solution:
def countBits(self, n: int) -> list[int]:
def count(n: int) -> int:
cnt = 0
while n > 0:
cnt += n % 2
n = n // 2
return cnt
output = []
for i in range(n + 1):
output.append(count(i))
return output
📊 시간/공간 복잡도 분석
피드백: 각 i에 대해 비트를 하나씩 세는 루프가 있어 전체 시간은 n의 비트 길이에 비례한다. 보통은 더 빠른 DP 방식이 가능하다. 개선 제안: 현재 구현이 적절해 보입니다.
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. 우리가 이전에 계산한 값들을 활용한다면 더 빠른 계산이 가능하지 않을까 해요 예를 들어 5의 경우 101이죠? 근데 이걸 오른쪽으로 쉬프트를 해주면 10이 되구요 이건 2가 될거에요 2의 1 비트 갯수가 1개라는것은 우리가 이전에 미리 계산해 둘수 있고, 101에서 맨 오른쪽 비트값이 1인지는 x & 1 같은 연산 혹은 x % 2 와 같은 연산으로 바로 확인이 가능하죠 이와 비슷하게 11011의 비트 갯수는 1101 + (11011의 마지막 비트가 1인가) 로 일반화 할수 있을거에요
Collaborator
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. 계산된 비트 사용하도록 최적화 해주었습니다~
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. 🏷️ 알고리즘 패턴 분석counting-bits/parkhojeong.pyclass Solution:
def countBits(self, n: int) -> list[int]:
if n == 0:
return [0]
arr = [0, 1]
def count(n: int) -> int:
return arr[n // 2] + n % 2
for i in range(2, n + 1):
arr.append(count(i))
return arr
📊 시간/공간 복잡도 분석
풀이 1:
|
| 복잡도 | |
|---|---|
| Time | O(n) |
| Space | O(n) |
피드백: 배열을 순차적으로 채우면서 각 수의 비트 수를 빠르게 계산합니다. 중간 함수 호출이 없어 상수-배열 접근으로 구성되어 있습니다.
개선 제안: 현재 구현이 적절해 보입니다.
풀이 2: Solution.countBits — Time: O(n) / Space: O(n)
| 복잡도 | |
|---|---|
| Time | O(n) |
| Space | O(n) |
피드백: arr과 내부 count 함수의 재귀적 의존 없이 순차적으로 값을 확정합니다.
개선 제안: 현재 구현이 적절해 보입니다.
💡 풀이에 시간/공간 복잡도를 주석으로 남겨보세요!
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,13 @@ | ||
| class Solution: | ||
| def countBits(self, n: int) -> list[int]: | ||
| if n == 0: | ||
| return [0] | ||
|
|
||
| arr = [0, 1] | ||
| def count(n: int) -> int: | ||
| return arr[n // 2] + n % 2 | ||
|
|
||
| for i in range(2, n + 1): | ||
| arr.append(count(i)) | ||
|
|
||
| return arr |
|
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. 🏷️ 알고리즘 패턴 분석house-robber-ii/parkhojeong.pyclass Solution:
def rob(self, nums: list[int]) -> int:
N = len(nums)
if N == 1:
return nums[0]
prefix_sum = [0] * (N + 1)
prefix_sum[1] = nums[0]
for i in range(2, N):
prefix_sum[i] = max(prefix_sum[i - 2] + nums[i - 1], prefix_sum[i - 1])
prefix_sum2 = [0] * (N + 1)
prefix_sum2[2] = nums[1]
for i in range(3, N + 1):
prefix_sum2[i] = max(prefix_sum2[i - 2] + nums[i - 1], prefix_sum2[i - 1])
return max(max(prefix_sum), max(prefix_sum2))
📊 시간/공간 복잡도 분석
피드백: 두 번째 배열 구간에 대한 동적 계획을 각각 수행하고 최댓값을 비교한다. 중복되는 계산을 피하면 된다. 개선 제안: 현재 구현이 적절해 보입니다.
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. 정말 깔끔하게 풀어주시긴 했는데요! 만약 실제 코딩 테스트에서 꼬리질문이 들어온다면 prefix sum의 경우에는 실제로 맨 앞 인덱스부터 자기 자신의 인덱스까지 값이 누적되어 있어야 하는데, 해당 경우에는 도둑이 집을 연달아 털 수 없어서 중간중간 끊기는 값이 저장되니까요! 그래서
Collaborator
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. 별도 함수를 선언해서 가독성을 좀 개선해봤습니다~
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. 🏷️ 알고리즘 패턴 분석house-robber-ii/parkhojeong.pyclass Solution:
def rob(self, nums: list[int]) -> int:
if len(nums) == 1:
return nums[0]
return max(
max(self.rob_linear(nums[:-1])),
max(self.rob_linear(nums[1:] ))
)
def rob_linear(self, nums: list[int]):
N = len(nums)
dp = [0] * (N + 1)
dp[1] = nums[0]
for i in range(2, N + 1):
dp[i] = max(dp[i - 2] + nums[i - 1], dp[i - 1])
return dp
📊 시간/공간 복잡도 분석
풀이 1:
|
| 복잡도 | |
|---|---|
| Time | O(n) |
| Space | O(n) |
피드백: 배열을 두 부분으로 나눠 각 부분에 대해 선형 다이나믹 프로그래밍을 적용합니다.
개선 제안: 현재 구현이 적절해 보입니다.
풀이 2: Solution.rob_linear — Time: O(n) / Space: O(n)
| 복잡도 | |
|---|---|
| Time | O(n) |
| Space | O(n) |
피드백: dp 배열을 이용해 각 위치까지의 최적 해를 누적 계산합니다.
개선 제안: 현재 구현이 적절해 보입니다.
💡 풀이에 시간/공간 복잡도를 주석으로 남겨보세요!
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,21 @@ | ||
| class Solution: | ||
| def rob(self, nums: list[int]) -> int: | ||
| if len(nums) == 1: | ||
| return nums[0] | ||
|
|
||
| return max( | ||
| max(self.rob_linear(nums[:-1])), | ||
| max(self.rob_linear(nums[1:] )) | ||
| ) | ||
|
|
||
| def rob_linear(self, nums: list[int]): | ||
| N = len(nums) | ||
|
|
||
| dp = [0] * (N + 1) | ||
| dp[1] = nums[0] | ||
|
|
||
| for i in range(2, N + 1): | ||
| dp[i] = max(dp[i - 2] + nums[i - 1], dp[i - 1]) | ||
|
|
||
|
|
||
| return dp |
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.
🏷️ 알고리즘 패턴 분석
binary-tree-level-order-traversal/parkhojeong.py
📊 시간/공간 복잡도 분석
피드백: 큐를 이용해 각 레벨의 노드를 처리하고 다음 레벨로 확장한다. 모든 노드를 한 번씩 방문하므로 시간 복잡도는 O(n), 추가 공간은 큐와 결과 저장으로 O(n)이다.
개선 제안: 현재 구현이 적절해 보입니다.