-
-
Notifications
You must be signed in to change notification settings - Fork 362
[parkhojeong] WEEK 07 Solutions #2795
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
872e5ed
b4b6029
a51c4ad
f0bdf21
f643ccf
3a04bda
f4fdb9b
86fa940
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. 제 생각엔 ans를 구하는것을 따로 분리해서 분기에 공통로직이 많은것 보다는 이렇게 경우를 크게 따지지 않고 전부 하는게 가독성이 좋지 않을까 라는 의견이 있습니다. 2개의 항목을 가지는 max 함수는 O(1)의 시간복잡도를 가지기 때문에 O(N) 루프 안에 돌려도 큰 성능상 문제가 없을것으로 보여서요
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. 🏷️ 알고리즘 패턴 분석longest-substring-without-repeating-characters/parkhojeong.pyclass Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
if s == "":
return 0
ch_to_idx = {}
start_idx = 0
i = 0
length_of_longest_substring = 1
for i in range(len(s)):
ch = s[i]
if ch in ch_to_idx and ch_to_idx[ch] >= start_idx:
start_idx = ch_to_idx[ch] + 1
ch_to_idx[ch] = i
else:
ch_to_idx[ch] = i
length_of_substring = i - start_idx + 1
length_of_longest_substring = max(length_of_longest_substring, length_of_substring)
return length_of_longest_substring
📊 시간/공간 복잡도 분석
피드백: 해시맵으로 마지막 등장 인덱스를 추적하고 윈도우 시작점을 중복 문자의 이전 위치로 갱신한다. 그러나 length_of_longest_substring 초기값과 부분 문자열 길이 계산 로직에서 혼선이 있어 실행 중 일부 경우에 잘못될 수 있다. 개선 제안: 초기값과 길이 계산 로직을 명확히 하여 모든 경우에 올바르게 동작하도록 수정하면 안정적이다. 예를 들어 length_of_substring 변수를 항상 i - start_idx + 1로 계산하고, 새로운 중복 발견 시 start_idx를 업데이트한 뒤 최장 길이를 반영.
|
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,22 @@ | ||
| class Solution: | ||
| def lengthOfLongestSubstring(self, s: str) -> int: | ||
| if s == "": | ||
| return 0 | ||
|
|
||
| ch_to_idx = {} | ||
| start_idx = 0 | ||
|
|
||
| i = 0 | ||
| length_of_longest_substring = 1 | ||
| for i in range(len(s)): | ||
| ch = s[i] | ||
| if ch in ch_to_idx and ch_to_idx[ch] >= start_idx: | ||
| start_idx = ch_to_idx[ch] + 1 | ||
| ch_to_idx[ch] = i | ||
| else: | ||
| ch_to_idx[ch] = i | ||
| length_of_substring = i - start_idx + 1 | ||
| length_of_longest_substring = max(length_of_longest_substring, length_of_substring) | ||
|
|
||
| return length_of_longest_substring | ||
|
|
|
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. 🏷️ 알고리즘 패턴 분석
📊 시간/공간 복잡도 분석
피드백: 그리드의 모든 원소를 한 번씩 방문하고, 섬의 연결 요소를 DFS로 탐색한다. 개선 제안: 재귀 깊이가 큰 입력에 대비해 비재귀 DFS나 BFS로 구현해 스택 오버플로를 피하는 방법을 고려해볼 수 있습니다.
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. 🏷️ 알고리즘 패턴 분석number-of-islands/parkhojeong.pyclass Solution:
def numIslands(self, grid: List[List[str]]) -> int:
row_len = len(grid)
col_len = len(grid[0])
def dfs(row: int, col: int):
if not (0 <= row < row_len and 0 <= col < col_len):
return
if grid[row][col] == "0":
return
grid[row][col] = "0"
dfs(row - 1, col)
dfs(row + 1, col)
dfs(row, col - 1)
dfs(row, col + 1)
num_islands = 0
for row in range(row_len):
for col in range(col_len):
if grid[row][col] == "1":
num_islands += 1
dfs(row, col)
return num_islands
📊 시간/공간 복잡도 분석
피드백: 전형적인 DFS 기반 섬 탐색으로 모든 셀을 한 번씩 방문한다. 재귀 깊이가 크게 증가하면 스택 오버플로 가능성이 있다. 개선 제안: 재귀 대신 명시적 스택을 사용한 DFS나 BFS로 구현하면 스택 깊이 문제를 피할 수 있다.
|
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,26 @@ | ||
| class Solution: | ||
| def numIslands(self, grid: List[List[str]]) -> int: | ||
| row_len = len(grid) | ||
| col_len = len(grid[0]) | ||
|
|
||
| def dfs(row: int, col: int): | ||
| if not (0 <= row < row_len and 0 <= col < col_len): | ||
| return | ||
|
|
||
| if grid[row][col] == "0": | ||
| return | ||
|
|
||
| grid[row][col] = "0" | ||
| dfs(row - 1, col) | ||
| dfs(row + 1, col) | ||
| dfs(row, col - 1) | ||
| dfs(row, col + 1) | ||
|
|
||
| num_islands = 0 | ||
| for row in range(row_len): | ||
| for col in range(col_len): | ||
| if grid[row][col] == "1": | ||
| num_islands += 1 | ||
| dfs(row, col) | ||
|
|
||
| return num_islands |
|
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. 🏷️ 알고리즘 패턴 분석
📊 시간/공간 복잡도 분석
피드백: 선행 노드 정보를 임시 저장하고 포인터를 차례로 뒤집어간다. 개선 제안: 현재 구현이 적절해 보입니다.
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. 🏷️ 알고리즘 패턴 분석reverse-linked-list/parkhojeong.py# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
prev_node, cur_node = None, head
while cur_node:
next_node = cur_node.next
cur_node.next = prev_node
prev_node, cur_node = cur_node, next_node
return prev_node
📊 시간/공간 복잡도 분석
피드백: 추가 데이터 구조 없이 링크를 뒤집어 나가는 표준 방법이다. 개선 제안: 특별한 개선 필요 없으며 현재 구현이 적절해 보인다.
|
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,16 @@ | ||
| # Definition for singly-linked list. | ||
| # class ListNode: | ||
| # def __init__(self, val=0, next=None): | ||
| # self.val = val | ||
| # self.next = next | ||
| class Solution: | ||
| def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]: | ||
| prev_node, cur_node = None, head | ||
|
|
||
| while cur_node: | ||
| next_node = cur_node.next | ||
|
|
||
| cur_node.next = prev_node | ||
| prev_node, cur_node = cur_node, next_node | ||
|
|
||
| return prev_node |
|
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. 🏷️ 알고리즘 패턴 분석
📊 시간/공간 복잡도 분석
피드백: 두 단계로 나눠 제로를 확산시키는 방식으로 in-place 해결을 시도했다. 개선 제안: 현재 구현이 적절해 보입니다.
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. 이거 재귀때문에 공간복잡도 O(max(m, n)) 일텐데 패턴분석이 이상하게 되어 있네요
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. 🏷️ 알고리즘 패턴 분석set-matrix-zeroes/parkhojeong.pyclass Solution:
def setZeroes(self, matrix: List[List[int]]) -> None:
"""
Do not return anything, modify matrix in-place instead.
"""
row_len = len(matrix)
col_len = len(matrix[0])
MARKER = "#"
def dfs(row, col, d_row, d_col):
if not (0 <= row < row_len and 0 <= col < col_len):
return
if matrix[row][col] == 0:
return
matrix[row][col] = MARKER
dfs(row + d_row, col + d_col, d_row, d_col)
for row in range(row_len):
for col in range(col_len):
if matrix[row][col] == 0:
matrix[row][col] = MARKER
dfs(row + 1, col, 1, 0)
dfs(row - 1, col, -1, 0)
dfs(row, col + 1, 0, 1)
dfs(row, col - 1, 0, -1)
for row in range(row_len):
for col in range(col_len):
if matrix[row][col] == MARKER:
matrix[row][col] = 0
📊 시간/공간 복잡도 분석
피드백: 현재 구현은 마커로 DFS를 활용해 연쇄적으로 0으로 바꾸는 비효율적 구조를 보인다. 여러 방향으로 확산시키는 DFS가 필요 이상으로 중복 방문을 유발할 수 있다. 개선 제안: 표준 접근인 첫 통과에서 행/열 배열에 플래그를 남겨 두고, 후처리에서 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. 🏷️ 알고리즘 패턴 분석set-matrix-zeroes/parkhojeong.pyclass Solution:
def setZeroes(self, matrix: List[List[int]]) -> None:
"""
Do not return anything, modify matrix in-place instead.
"""
row_len = len(matrix)
col_len = len(matrix[0])
MARKER = sys.maxsize
def dfs(row, col, d_row, d_col):
if not (0 <= row < row_len and 0 <= col < col_len):
return
if matrix[row][col] == 0:
return
matrix[row][col] = MARKER
dfs(row + d_row, col + d_col, d_row, d_col)
for row in range(row_len):
for col in range(col_len):
if matrix[row][col] == 0:
matrix[row][col] = MARKER
dfs(row + 1, col, 1, 0)
dfs(row - 1, col, -1, 0)
dfs(row, col + 1, 0, 1)
dfs(row, col - 1, 0, -1)
for row in range(row_len):
for col in range(col_len):
if matrix[row][col] == MARKER:
matrix[row][col] = 0
📊 시간/공간 복잡도 분석
피드백: 0이 있는 위치를 기준으로 인접 방향으로 탐색해 MARKER를 거쳐 간접적으로 표시한다. 하지만 모든 0을 찾고 마커 처리까지 가능하므로 총 시간은 이중 루프로 결정되고 공간은 추가 배열 없이 마커를 사용해 구현한다. 개선 제안: 현재 구현은 in-place 처리가 가능하나, O(1) 추가 공간으로 구현하려면 행/열 마커를 따로 두지 않고 첫 줄에서 처리 여부를 추적하는 방식으로 개선할 수 있습니다.
|
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,34 @@ | ||
| class Solution: | ||
| def setZeroes(self, matrix: List[List[int]]) -> None: | ||
| """ | ||
| Do not return anything, modify matrix in-place instead. | ||
| """ | ||
|
|
||
| row_len = len(matrix) | ||
| col_len = len(matrix[0]) | ||
| MARKER = sys.maxsize | ||
|
|
||
| def dfs(row, col, d_row, d_col): | ||
| if not (0 <= row < row_len and 0 <= col < col_len): | ||
| return | ||
|
|
||
| if matrix[row][col] == 0: | ||
| return | ||
|
|
||
| matrix[row][col] = MARKER | ||
|
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. 파이썬이라 가능하다지만, 정수 행렬에 문자열을 넣는것은 좀 별로이지 않을까 싶습니다.
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. 같은 타입 중 입력 값 범위에 해당하지 않는 sys.maxsize 쓰도록 변경했습니다. |
||
| dfs(row + d_row, col + d_col, d_row, d_col) | ||
|
|
||
| for row in range(row_len): | ||
| for col in range(col_len): | ||
| if matrix[row][col] == 0: | ||
|
|
||
| matrix[row][col] = MARKER | ||
| dfs(row + 1, col, 1, 0) | ||
| dfs(row - 1, col, -1, 0) | ||
| dfs(row, col + 1, 0, 1) | ||
| dfs(row, col - 1, 0, -1) | ||
|
|
||
| for row in range(row_len): | ||
| for col in range(col_len): | ||
| if matrix[row][col] == MARKER: | ||
| matrix[row][col] = 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. 🏷️ 알고리즘 패턴 분석
📊 시간/공간 복잡도 분석
피드백: 왼쪽 위에서 오른쪽 아래로 경로의 수를 누적 합으로 구한다. 개선 제안: 현재 구현이 적절해 보입니다.
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. 칸 채운다고 생각하시면 복잡한 if 없이도 충분히 가능하세요! 그리고
인 풀이도 있으니까 해보시면 좋을것 같네요
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. O(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. 🏷️ 알고리즘 패턴 분석unique-paths/parkhojeong.pyclass Solution:
def uniquePaths(self, m: int, n: int) -> int:
column = [1] * m
for col in range(n - 1):
for row in range(1, m):
column[row] = column[row] + column[row - 1]
return column[-1]
📊 시간/공간 복잡도 분석
피드백: 1차원 DP 배열로 메모리 사용을 최소화한 점은 좋다. 개선 제안: 명확성을 위해 주석으로 점화식을 추가하면 이해도가 상승한다.
|
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,10 @@ | ||
| class Solution: | ||
| def uniquePaths(self, m: int, n: int) -> int: | ||
| column = [1] * m | ||
|
|
||
| for col in range(n - 1): | ||
|
|
||
| for row in range(1, m): | ||
| column[row] = column[row] + column[row - 1] | ||
|
|
||
| return column[-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.
🏷️ 알고리즘 패턴 분석
📊 시간/공간 복잡도 분석
피드백: 문자 인덱스 저장소를 사용해 각 문자 마지막 위치를 추적하고, 중복이 등장하면 시작 인덱스를 갱신한다.
개선 제안: 현재 구현이 적절해 보입니다.