-
-
Notifications
You must be signed in to change notification settings - Fork 361
[Chanz] WEEK 04 Solutions #2753
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
76b95a9
1403468
d532ed4
06931e4
8709455
b4381e3
0ad1fc7
ed663a6
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,15 @@ | ||
| class Solution: | ||
| def findMin(self, nums: List[int]) -> int: | ||
|
|
||
| left = 0 | ||
| right = len(nums) - 1 | ||
|
|
||
| while left < right: | ||
| mid = (left + right) // 2 | ||
|
|
||
| if nums[right] < nums[mid]: # right 와 mid 사이에 최소 값이 존재 | ||
|
Comment on lines
+7
to
+10
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. 정렬 된 경우인 경우 바로 반환하도록 했습니다. Leetcode에서는 기존 코드도 0ms라서.. 직접 성능 비교는 어렵군요..! 의도하신 바가 이게 맞을지 궁금하긴 합니다..ㅎㅎ |
||
| left = mid + 1 | ||
| else: | ||
| right = mid | ||
|
|
||
| return nums[left] | ||
|
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. 🏷️ 알고리즘 패턴 분석
|
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,25 @@ | ||
| # 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 maxDepth(self, root: Optional[TreeNode]) -> int: | ||
|
|
||
| max_depth = 0 | ||
| def dfs(cur_node, cur_depth): | ||
| nonlocal max_depth | ||
| if cur_node == None: | ||
| return | ||
| cur_depth += 1 | ||
| max_depth = max(max_depth, cur_depth) | ||
|
|
||
| dfs(cur_node.left, cur_depth) | ||
| dfs(cur_node.right, cur_depth) | ||
| return | ||
|
|
||
| dfs(root, 0) | ||
| return max_depth | ||
|
Comment on lines
+9
to
+24
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. 개인적으로 외부 변수 max_depth, nonlocal 때문에 그런지 코드 따라가기가 약간 어려웠던거 같습니다. dfs 함수의 리턴 값을 활용하시면 가독성을 많이 올리실 수 있을 거 같습니다. |
||
|
|
||
|
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. 확실히 이 문제에서는 BFS보다는 DFS가 더 좋은 풀이 같네요! |
||
|
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. 🏷️ 알고리즘 패턴 분석
|
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,33 @@ | ||
| # Definition for singly-linked list. | ||
| # class ListNode: | ||
| # def __init__(self, val=0, next=None): | ||
| # self.val = val | ||
| # self.next = next | ||
| class Solution: | ||
| def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]: | ||
|
|
||
| if not list1: | ||
| return list2 | ||
| if not list2: | ||
| return list1 | ||
|
|
||
| cursor = ListNode() | ||
| result = cursor | ||
| cursor.next = list1 | ||
|
|
||
| while cursor.next: | ||
| while list2 and list2.val <= cursor.next.val: | ||
| temp_1 = cursor.next | ||
| temp_2 = list2.next | ||
|
|
||
| cursor.next = list2 | ||
| list2.next = temp_1 | ||
| list2 = temp_2 | ||
|
|
||
| cursor = cursor.next | ||
|
|
||
| if list2: | ||
| cursor.next = list2 | ||
|
Comment on lines
+18
to
+30
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. cursor에 어떤 값이 담기고 list2와 어떻게 비교되어서 동작하는건지 따라가기가 조금 어려운 거 같습니다. 스왑 로직도 있고 해서 그런 거 같은데 조금 더 단순하게 풀어보셔도 좋을 거 같습니다.
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. 맞습니다. 저도 구현하면서 스왑하고 이런게 헷갈리더라고요. |
||
|
|
||
| return result.next | ||
|
|
||
|
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. 🏷️ 알고리즘 패턴 분석
|
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,32 @@ | ||
| class Solution: | ||
| def exist(self, board: List[List[str]], word: str) -> bool: | ||
|
|
||
| def dfs(current, word_idx): | ||
| x, y = current | ||
|
|
||
| if word_idx == len(word): | ||
| return True | ||
|
|
||
| if x < 0 or x >= len(board) or y < 0 or y >= len(board[0]): | ||
| return False | ||
|
|
||
| if board[x][y] != word[word_idx] : | ||
| return False | ||
|
|
||
| tmp = board[x][y] | ||
| board[x][y] = '#' | ||
|
|
||
| found = (dfs((x-1, y), word_idx+1) or | ||
| dfs((x+1, y), word_idx+1) or | ||
| dfs((x, y-1), word_idx+1) or | ||
| dfs((x, y+1), word_idx+1)) | ||
|
|
||
| board[x][y] = tmp | ||
|
|
||
| return found | ||
|
Comment on lines
+4
to
+26
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. 요거 돌려보면 runtime이 50% 정도 나오는데 최적화 시도해보셔도 좋을 거 같습니다. 불필요한 탐색을 안하도록 해보시면 될 거 같아요. |
||
|
|
||
| for x, rows in enumerate(board): | ||
| for y, cell in enumerate(rows): | ||
| if dfs((x, y), 0) == True : | ||
| return True | ||
| return False | ||
|
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로 풀 수 있다는 것은 전혀 생각하지 못했네요...! 감사합니다! |
||
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:
Solution.findMin— Time: O(log n) / Space: O(1)피드백: 중단 조건이 left < right 이고, 매 반복마다 중간값과 오른쪽 끝 값을 비교해 범위를 절반으로 축소합니다.
개선 제안: 현재 구현이 적절해 보입니다.
풀이 2:
Solution.maxDepth— Time: O(n) / Space: O(h)피드백: 재귀적인 DFS로 각 노드를 한 번씩 방문하고 스택 프레임으로 깊이를 추적합니다.
개선 제안: 현재 구현이 적절해 보입니다.
풀이 3:
Solution.mergeTwoLists— Time: O(n + m) / Space: O(1)피드백: 비교를 통해 노드를 재배치하여 더미 노드를 가운데에 두고 연결 리스트를 확장합니다.
개선 제안: 현재 구현이 적절해 보입니다.
풀이 4:
Solution.exist— Time: O(4^(L) * NM) / Space: O(L)피드백: 각 좌표에서 DFS를 진행하고 방문 처리를 위해 문자를 임시로 바꿔 재귀적으로 탐색합니다.
개선 제안: 현재 구현이 적절해 보입니다.