-
-
Notifications
You must be signed in to change notification settings - Fork 195
[yyyyyyyyyKim] WEEK 11 solutions #1568
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
Merged
Merged
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
de2f726
missing-number solution
yyyyyyyyyKim ecb1def
missing-number solution
yyyyyyyyyKim 8429f77
reorder-list solution
yyyyyyyyyKim 1f00216
merge-intervals solution
yyyyyyyyyKim 85ab3a9
graph-valid-tree solution
yyyyyyyyyKim a2cd9c2
binary-tree-maximum-path-sum solution
yyyyyyyyyKim File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,30 @@ | ||
# 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: | ||
|
||
# DFS + 분할정복형 DP | ||
# 시간복잡도 O(n), 공간복잡도 O(n) | ||
self.answer = float('-inf') # 최저값을 초기값으로 세팅(dfs함수에서도 쓰일 수 있게 인스턴스변수 선언해서 전역변수처럼 사용) | ||
|
||
def dfs(node): | ||
if not node: | ||
return 0 | ||
|
||
# 왼쪽, 오른쪽 서브트리에서 최대합(음수라면 버리고 0 가져가기) | ||
left = max(0,dfs(node.left)) | ||
right = max(0,dfs(node.right)) | ||
|
||
# 현재 노드를 포함하는 최대합으로 answer 업데이트 | ||
self.answer = max(self.answer, left + right + node.val) | ||
|
||
# 왼쪽,오른쪽 중 최대값 선택(한방향이니까)해서 부모에게 리턴 | ||
return max(left, right) + node.val | ||
|
||
|
||
dfs(root) | ||
return self.answer |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,46 @@ | ||
from typing import ( | ||
List, | ||
) | ||
|
||
class Solution: | ||
""" | ||
@param n: An integer | ||
@param edges: a list of undirected edges | ||
@return: true if it's a valid tree, or false | ||
""" | ||
def valid_tree(self, n: int, edges: List[List[int]]) -> bool: | ||
# DFS(그래프 탐색) | ||
# 시간복잡도 O(n), 공간복잡도 O(n) | ||
|
||
# 트리의 간선 수는 항상 "노드 수 -1"(아니면 바로 False) | ||
if len(edges) != n-1: | ||
return False | ||
|
||
# 인접 리스트 방식으로 그래프 생성 | ||
graph = [[] for _ in range(n)] | ||
for i, j in edges: | ||
graph[i].append(j) | ||
graph[j].append(i) | ||
|
||
# set사용(방문여부만 빠르게 탐색(in연산 시간복잡도 O(1)) | ||
visited = set() | ||
|
||
def dfs(node,prev): | ||
# 이미 방문한 노드면 종료 | ||
if node in visited: | ||
return | ||
visited.add(node) | ||
|
||
# 현재 노드와 이웃 탐색 | ||
for i in graph[node]: | ||
# 바로 이전 노드 패스(무방향 그래프니까) | ||
if i == prev: | ||
continue | ||
dfs(i, node) | ||
|
||
|
||
# 0번 노드부터 탐색 시작 | ||
dfs(0, -1) | ||
|
||
# 방문한 노드 수와 전체 노드 수가 같으면 연결 그래프 -> 트리 | ||
return len(visited) == n |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,18 @@ | ||
class Solution: | ||
def merge(self, intervals: List[List[int]]) -> List[List[int]]: | ||
# 시간복잡도 O(n log n), 공간복잡도 O(n) | ||
|
||
intervals.sort() # 정렬 | ||
answer = [] | ||
|
||
for i in intervals: | ||
|
||
# answer가 비어있거나 answer의 맨 뒤 값이 i의 첫 번째 값보다 작을 경우(겹치지않는경우) answer에 i추가 | ||
if not answer or answer[-1][1] < i[0]: | ||
answer.append(i) | ||
|
||
# 값이 겹치는 경우 합치기(더 큰 값으로 업데이트) | ||
else: | ||
answer[-1][1] = max(answer[-1][1],i[1]) | ||
|
||
return answer |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,8 @@ | ||
class Solution: | ||
def missingNumber(self, nums: List[int]) -> int: | ||
|
||
# 시간복잡도 O(n), 공간복잡도 O(1) | ||
# n = nums의 길이 | ||
# 0부터 n까지 총합 = (n*(n+1))//2 | ||
# 총합에서 nums의 합을 빼면 빠진 수를 구할 수 있음 | ||
return (len(nums)*(len(nums)+1))//2 - sum(nums) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,42 @@ | ||
# Definition for singly-linked list. | ||
# class ListNode: | ||
# def __init__(self, val=0, next=None): | ||
# self.val = val | ||
# self.next = next | ||
class Solution: | ||
def reorderList(self, head: Optional[ListNode]) -> None: | ||
""" | ||
Do not return anything, modify head in-place instead. | ||
""" | ||
# 시간복잡도 o(n), 공간복잡도 O(1) | ||
|
||
# 리스트 중간 지점 찾기 | ||
slow, fast = head, head | ||
|
||
while fast and fast.next: | ||
slow = slow.next | ||
fast = fast.next.next | ||
|
||
# 중간에서 뒷부분 뒤집기 | ||
curr = slow.next | ||
prev = None | ||
slow.next = None | ||
|
||
while curr: | ||
next_temp = curr.next | ||
curr.next = prev | ||
prev = curr | ||
curr = next_temp | ||
|
||
# 앞부분과 뒷부분 합치기 | ||
first, second = head, prev | ||
|
||
while second: | ||
temp1 = first.next | ||
temp2 = second.next | ||
|
||
first.next = second | ||
second.next = temp1 | ||
|
||
first = temp1 | ||
second = temp2 |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
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.
저는 boolean 배열로 방문 여부를 체크해서 풀었는데, 총 합이 동일한지 여부로 풀면 이렇게 간단한 한 줄 풀이도 가능하네요. 제 reviewer깨서도 동일한 방법을 조언해주셨는데, 이렇게 간략한 풀이를 보니 좀 더 직관적으로 와닿았습니다. ㅎㅎ