-
-
Notifications
You must be signed in to change notification settings - Fork 195
[EGON] Week11 Solutions #554
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
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,67 @@ | ||
from typing import Optional | ||
from unittest import TestCase, main | ||
|
||
|
||
# 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 maxPathSum(self, root: Optional[TreeNode]) -> int: | ||
return self.solve_dfs(root) | ||
|
||
""" | ||
Runtime: 11 ms (Beats 98.62%) | ||
Time Complexity: O(n) | ||
> dfs를 통해 모든 node를 방문하므로 O(n) | ||
|
||
Memory: 22.10 MB (Beats 10.70%) | ||
Space Complexity: O(n) | ||
- dfs 재귀 호출 스택의 깊이는 이진트리가 최악으로 편향된 경우 O(n), upper bound | ||
- 나머지 변수는 O(1) | ||
> O(n), upper bound | ||
""" | ||
def solve_dfs(self, root: Optional[TreeNode]) -> int: | ||
max_path_sum = float('-inf') | ||
|
||
def dfs(node: Optional[TreeNode]) -> int: | ||
nonlocal max_path_sum | ||
|
||
if not node: | ||
return 0 | ||
|
||
max_left = max(dfs(node.left), 0) | ||
max_right = max(dfs(node.right), 0) | ||
max_path_sum = max(max_path_sum, node.val + max_left + max_right) | ||
|
||
return node.val + max(max_left, max_right) | ||
|
||
dfs(root) | ||
|
||
return max_path_sum | ||
|
||
|
||
class _LeetCodeTestCases(TestCase): | ||
def test_1(self): | ||
root = TreeNode(-10) | ||
node_1 = TreeNode(9) | ||
node_2 = TreeNode(20) | ||
node_3 = TreeNode(15) | ||
node_4 = TreeNode(7) | ||
node_2.left = node_3 | ||
node_2.right = node_4 | ||
root.left = node_1 | ||
root.right = node_2 | ||
|
||
# root = [-10, 9, 20, None, None, 15, 7] | ||
output = 42 | ||
|
||
self.assertEqual(Solution().maxPathSum(root), output) | ||
|
||
|
||
if __name__ == '__main__': | ||
main() |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,83 @@ | ||
from typing import List | ||
from unittest import TestCase, main | ||
|
||
|
||
class ListNode: | ||
def __init__(self, val=0, next=None): | ||
self.val = val | ||
self.next = next | ||
|
||
|
||
class Solution: | ||
def valid_tree(self, n: int, edges: List[List[int]]) -> bool: | ||
return self.solve_union_find(n, edges) | ||
|
||
""" | ||
LintCode 로그인이 안되어서 https://neetcode.io/problems/valid-tree에서 실행시키고 통과만 확인했습니다. | ||
|
||
Runtime: ? ms (Beats ?%) | ||
Time Complexity: O(max(m, n)) | ||
- UnionFind의 parent 생성에 O(n) | ||
- edges 조회에 O(m) | ||
- Union-find 알고리즘의 union을 매 조회마다 사용하므로, * O(α(n)) (α는 아커만 함수의 역함수) | ||
- UnionFind의 모든 노드가 같은 부모, 즉 모두 연결되어 있는지 확인하기 위해, n번 find에 O(n * α(n)) | ||
> O(n) + O(m * α(n)) + O(n * α(n)) ~= O(max(m, n) * α(n)) ~= O(max(m, n)) (∵ α(n) ~= C) | ||
|
||
Memory: ? MB (Beats ?%) | ||
Space Complexity: O(n) | ||
- UnionFind의 parent와 rank가 크기가 n인 리스트이므로, O(n) + O(n) | ||
> O(n) + O(n) ~= O(n) | ||
""" | ||
def solve_union_find(self, n: int, edges: List[List[int]]) -> bool: | ||
|
||
class UnionFind: | ||
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. 오 유니온파인드를 클래스로 만들어두고 풀이하셨네요 |
||
def __init__(self, size: int): | ||
self.parent = [i for i in range(size)] | ||
self.rank = [1] * size | ||
|
||
def union(self, first: int, second: int) -> bool: | ||
first_parent, second_parent = self.find(first), self.find(second) | ||
if first_parent == second_parent: | ||
return False | ||
|
||
if self.rank[first_parent] > self.rank[second_parent]: | ||
self.parent[second_parent] = first_parent | ||
elif self.rank[first_parent] < self.rank[second_parent]: | ||
self.parent[first_parent] = second_parent | ||
else: | ||
self.parent[second_parent] = first_parent | ||
self.rank[first_parent] += 1 | ||
|
||
return True | ||
|
||
def find(self, node: int): | ||
if self.parent[node] != node: | ||
self.parent[node] = self.find(self.parent[node]) | ||
|
||
return self.parent[node] | ||
|
||
unionFind = UnionFind(size=n) | ||
for first, second in edges: | ||
is_cycle = unionFind.union(first, second) is False | ||
if is_cycle: | ||
return False | ||
|
||
root = unionFind.find(0) | ||
for i in range(1, n): | ||
if unionFind.find(i) != root: | ||
return False | ||
Comment on lines
+65
to
+68
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. 이 부분은 edges의 길이가 N-1개 미만인지 아닌지로 체크할 수도 있지만, union-find 쓰는데 통일해서 사용했습니다 |
||
|
||
return True | ||
|
||
|
||
class _LeetCodeTestCases(TestCase): | ||
def test_1(self): | ||
n = 5 | ||
edges = [[0, 1], [1, 2], [2, 3], [1, 3], [1, 4]] | ||
output = False | ||
|
||
self.assertEqual(Solution().valid_tree(n, edges), output) | ||
|
||
|
||
if __name__ == '__main__': | ||
main() |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,66 @@ | ||
from bisect import bisect_left | ||
from typing import List | ||
from unittest import TestCase, main | ||
|
||
|
||
class Solution: | ||
def insert(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]: | ||
return self.solve(intervals, newInterval) | ||
|
||
""" | ||
Runtime: 1 ms (Beats 95.76%) | ||
Time Complexity: O(n) | ||
> intervals의 전체를 선형적으로 조회하므로 O(n), 그 외의 append등의 연산들은 O(1)이므로 무시 | ||
|
||
Memory: 18.70 MB (Beats 99.60%) | ||
Space Complexity: O(n) | ||
> result의 크기는 intervals와 newInterval이 하나도 겹치지 않는 경우, 최대 n + 1이므로, O(n + 1) ~= O(n) | ||
""" | ||
def solve(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]: | ||
if not intervals: | ||
return [newInterval] | ||
|
||
result = [] | ||
new_s, new_e = newInterval | ||
for interval in intervals: | ||
s, e = interval | ||
if e < new_s: | ||
result.append(interval) | ||
elif new_e < s: | ||
if new_s != -1 and new_e != -1: | ||
result.append([new_s, new_e]) | ||
new_s = new_e = -1 | ||
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. -1이 뭔가 했네요. |
||
|
||
result.append(interval) | ||
else: | ||
new_s = min(new_s, s) | ||
new_e = max(new_e, e) | ||
|
||
if new_s != -1 and new_e != -1: | ||
result.append([new_s, new_e]) | ||
|
||
return result | ||
|
||
|
||
class _LeetCodeTestCases(TestCase): | ||
def test_1(self): | ||
intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]] | ||
newInterval = [4,8] | ||
output = [[1,2],[3,10],[12,16]] | ||
self.assertEqual(Solution().insert(intervals, newInterval), output) | ||
|
||
def test_2(self): | ||
intervals = [[1,2]] | ||
newInterval = [3,4] | ||
output = [[1,2], [3,4]] | ||
self.assertEqual(Solution().insert(intervals, newInterval), output) | ||
|
||
def test_3(self): | ||
intervals = [[1,3], [5,6]] | ||
newInterval = [4,5] | ||
output = [[1,3], [4,6]] | ||
self.assertEqual(Solution().insert(intervals, newInterval), output) | ||
|
||
|
||
if __name__ == '__main__': | ||
main() |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,80 @@ | ||
from typing import Optional | ||
from unittest import TestCase, main | ||
|
||
|
||
# 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: | ||
return self.solve_dfs_iterable(root) | ||
|
||
""" | ||
Runtime: 0 ms (Beats 100.00%) | ||
Time Complexity: O(n) | ||
> 트리의 모든 노드의 갯수를 n개라고 하면, 트리의 모든 노드를 stack에 넣어 조회하므로 O(n) | ||
|
||
Memory: 17.75 MB (Beats 21.97%) | ||
Space Complexity: O(n) | ||
> 최악의 경우 트리의 최대 길이가 n인 경우이므로, stack의 최대 크기가 n에 비례하므로 O(n), upper bound | ||
""" | ||
def solve_dfs_iterable(self, root: Optional[TreeNode]) -> int: | ||
max_depth = 0 | ||
stack = [(root, 0)] | ||
while stack: | ||
curr_node, curr_depth = stack.pop() | ||
if curr_node is None: | ||
continue | ||
|
||
if curr_node.left is None and curr_node.right is None: | ||
max_depth = max(max_depth, curr_depth + 1) | ||
continue | ||
|
||
if curr_node.left: | ||
stack.append((curr_node.left, curr_depth + 1)) | ||
if curr_node.right: | ||
stack.append((curr_node.right, curr_depth + 1)) | ||
|
||
return max_depth | ||
|
||
|
||
""" | ||
Runtime: 0 ms (Beats 100.00%) | ||
Time Complexity: O(n) | ||
|
||
Memory: 17.90 MB (Beats 9.05%) | ||
Space Complexity: O(n) | ||
""" | ||
def solve_dfs_recursive(self, root: Optional[TreeNode]) -> int: | ||
max_depth = 0 | ||
|
||
def dfs(node: Optional[TreeNode], depth: int): | ||
nonlocal max_depth | ||
|
||
if not node: | ||
return max_depth | ||
|
||
if node.left is None and node.right is None: | ||
max_depth = max(max_depth, depth + 1) | ||
return | ||
|
||
dfs(node.left, depth + 1) | ||
dfs(node.right, depth + 1) | ||
|
||
dfs(root, 0) | ||
|
||
return max_depth | ||
|
||
|
||
class _LeetCodeTestCases(TestCase): | ||
def test_1(self): | ||
self.assertEqual(True, True) | ||
|
||
|
||
if __name__ == '__main__': | ||
main() |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,71 @@ | ||
from heapq import heappush, heappop | ||
from typing import List, Optional | ||
from unittest import TestCase, main | ||
|
||
|
||
class ListNode: | ||
def __init__(self, val=0, next=None): | ||
self.val = val | ||
self.next = next | ||
|
||
|
||
class Solution: | ||
def reorderList(self, head: Optional[ListNode]) -> None: | ||
return self.solve(head) | ||
|
||
""" | ||
Runtime: 15 ms (Beats 88.30%) | ||
Time Complexity: O(n) | ||
- 역방향 링크드 리스트인 backward를 생성하는데, 원본 링크드 리스트의 모든 노드를 조회하는데 O(n) | ||
- reorder하는데 원본 링크드 리스트의 모든 노드의 길이만큼 backward와 forward의 노드들을 조회하는데 O(n) | ||
> O(n) + O(n) = 2 * O(n) ~= O(n) | ||
|
||
Memory: 23.20 MB (Beats 88.27%) | ||
Space Complexity: O(n) | ||
> 역방향 링크드 리스트인 backward를 생성하는데, backward의 길이는 원본 링크드 리스트의 길이와 같으므로 O(n) | ||
""" | ||
def solve(self, head: Optional[ListNode]) -> None: | ||
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. 오 다른분들과 다른 새로운 풀이네요! 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. backward를 생성하는 풀이방법 충분히 납득되는 풀이방법이네요.👍 |
||
backward = ListNode(head.val) | ||
backward_node = head.next | ||
length = 1 | ||
while backward_node: | ||
length += 1 | ||
temp_node = ListNode(backward_node.val) | ||
temp_node.next = backward | ||
backward = temp_node | ||
backward_node = backward_node.next | ||
|
||
node = head | ||
forward = head.next | ||
for i in range(length): | ||
if i == length - 1: | ||
node.next = None | ||
return | ||
|
||
if i % 2 == 0: | ||
node.next = backward | ||
backward = backward.next | ||
node = node.next | ||
else: | ||
node.next = forward | ||
forward = forward.next | ||
node = node.next | ||
|
||
|
||
class _LeetCodeTestCases(TestCase): | ||
def test_1(self): | ||
node_1 = ListNode(1) | ||
node_2 = ListNode(2) | ||
node_3 = ListNode(3) | ||
node_4 = ListNode(4) | ||
node_5 = ListNode(5) | ||
node_1.next = node_2 | ||
node_2.next = node_3 | ||
node_3.next = node_4 | ||
node_4.next = node_5 | ||
|
||
self.assertEqual(Solution().reorderList(node_1), True) | ||
|
||
|
||
if __name__ == '__main__': | ||
main() |
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.
설명을 자세히 적어주셔서 좋네요! 감사합니다!
다만 이 문제의 경우 edges.length = n-1이라는 조건이 있으니, O(n)으로 단순화 할 수 있을것으로 보입니다!
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.
간선의 총 갯수가 n-1개가 아닌 케이스가 있었던 것 같은데... 예를 들어 서로 분리된 유효한 트리 2개인 경우나, example2의 TC도 있었습니다.
Input: n = 5 edges = [[0, 1], [1, 2], [2, 3], [1, 3], [1, 4]]
Output: false.