-
-
Notifications
You must be signed in to change notification settings - Fork 335
[hyeri0903] WEEK11 Solutions #2597
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
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,48 @@ | ||
| /** | ||
| * Definition for a binary tree node. | ||
| * public class TreeNode { | ||
| * int val; | ||
| * TreeNode left; | ||
| * TreeNode right; | ||
| * TreeNode() {} | ||
| * TreeNode(int val) { this.val = val; } | ||
| * TreeNode(int val, TreeNode left, TreeNode right) { | ||
| * this.val = val; | ||
| * this.left = left; | ||
| * this.right = right; | ||
| * } | ||
| * } | ||
| */ | ||
| class Solution { | ||
| int maxValue = Integer.MIN_VALUE; | ||
|
|
||
| public int maxPathSum(TreeNode root) { | ||
| /** | ||
| 1.노드의 sum이 가장 최대가 되는 path 의 maximum sum 찾기 | ||
| 2.solution : DFS | ||
| */ | ||
|
|
||
| dfs(root); | ||
| return maxValue; | ||
|
|
||
| } | ||
|
|
||
| private int dfs(TreeNode node) { | ||
| if(node == null) { | ||
| return 0; | ||
| } | ||
|
|
||
| int left = Math.max(0, dfs(node.left)); | ||
| int right = Math.max(0, dfs(node.right)); | ||
|
|
||
| //현재 노드를 중심으로하는 Path | ||
| int currPath = left + node.val + right; | ||
|
|
||
| //update max value | ||
| maxValue = Math.max(maxValue, currPath); | ||
|
|
||
| //부모 노드에게 최대값 전달 | ||
| return node.val + Math.max(left, right); | ||
| } | ||
|
|
||
| } |
|
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를 통해 방문 여부를 체크하며 사이클 존재 여부와 모든 노드가 연결되어 있는지 확인합니다. 간선 수와 노드 수에 따라 시간과 공간 복잡도가 결정됩니다. 개선 제안: 현재 구현이 적절해 보입니다.
|
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,63 @@ | ||
| public class Solution { | ||
| /** | ||
| * @param n: An integer | ||
| * @param edges: a list of undirected edges | ||
| * @return: true if it's a valid tree, or false | ||
| */ | ||
| public boolean validTree(int n, int[][] edges) { | ||
| /** | ||
| 1. n개의 노드 valid tree 검사 | ||
| 2. constraints | ||
| - no cycle | ||
| - all nodes are connected | ||
| 3. Solution: DFS | ||
| - 간선 개수 체크 | ||
| - 그래프 만들어서 cycle 없고 && 모두 방문했는지 체크 | ||
| 너모 어려워요... | ||
| */ | ||
|
|
||
| //간선 개수 체크 | ||
| if(edges.length != n-1) { | ||
| return false; | ||
| } | ||
|
|
||
| //그래프 만들기 | ||
| List<List<Integer>> graph = new ArrayList<>(); | ||
|
|
||
| for(int i = 0; i < n; i++) { | ||
| graph.add(new ArrayList<>()); | ||
| } | ||
| for(int[] edge: edges) { | ||
| int a = edge[0]; | ||
| int b = edge[1]; | ||
| graph.get(a).add(b); | ||
| graph.get(b).add(a); | ||
| } | ||
| //check through DFS | ||
| Set<Integer> visited = new HashSet<>(); | ||
|
|
||
| if(hasCycle(0, -1, graph, visited)) { | ||
| return false; | ||
| } | ||
| if(visited.size() != n) { | ||
| return false; | ||
| } | ||
| return true; | ||
| } | ||
| private boolean hasCycle(int node, int parent, List<List<Integer>> graph, Set<Integer> visited) { | ||
| //이미 방문했으면 cycle | ||
| if(visited.contains(node)) { | ||
| return true; | ||
| } | ||
| visited.add(node); | ||
| for(int neighbor: graph.get(node)) { | ||
| if(neighbor == parent) { | ||
| continue; | ||
| } | ||
| if(hasCycle(neighbor, node, graph, visited)) { | ||
| 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. 🏷️ 알고리즘 패턴 분석
📊 시간/공간 복잡도 분석
피드백: 배열을 시작값 기준으로 정렬하고, 정렬된 배열을 순회하며 겹치는 구간을 병합합니다. 정렬이 시간 복잡도를 지배하며, 병합 결과는 별도 리스트에 저장됩니다. 개선 제안: 현재 구현이 적절해 보입니다.
|
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,40 @@ | ||
| class Solution { | ||
| public int[][] merge(int[][] intervals) { | ||
| /** | ||
| 1.prob: overlapping 되는 곳을 merge 해서 return | ||
| 2.constraints | ||
| - len(intervalse) min = 1, max= 10000 | ||
| - start, end value min = 0, max = 10000 | ||
| 3.solution | ||
| - sorting array -> merge overlapping values | ||
| time: O(n log n) | ||
| */ | ||
|
|
||
| int n = intervals.length; | ||
| Arrays.sort(intervals, (a,b) -> Integer.compare(a[0], b[0])); | ||
|
|
||
| List<int[]> answer = new ArrayList<>(); | ||
| int start = intervals[0][0]; | ||
| int end = intervals[0][1]; | ||
|
|
||
| for(int i = 1; i < n; i++) { | ||
| int nextStart = intervals[i][0]; | ||
| int nextEnd = intervals[i][1]; | ||
|
|
||
| //overlap | ||
| if(end >= nextStart) { | ||
| end = Math.max(end, nextEnd); | ||
| } else { | ||
| answer.add(new int[]{start, end}); | ||
|
|
||
| start = nextStart; | ||
| end = nextEnd; | ||
|
|
||
| } | ||
| } | ||
|
|
||
| //last intervals | ||
| answer.add(new int[]{start, end}); | ||
| return answer.toArray(new int[answer.size()][]); | ||
| } | ||
| } |
|
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,30 @@ | ||
| class Solution { | ||
| public int missingNumber(int[] nums) { | ||
| /** | ||
| 1.distinc number 로 이루어진 0~n 까지의 배열 중 missing number return | ||
| 2.constraints | ||
| - n 최소 = 1, 최대 = 10000 | ||
| - 배열길이 min=0, max=n | ||
| 3.solutions | ||
| - sorting 하고 for문으로 missing num check. time: O(n log n), space: O(1) | ||
| - 전체 sum - 실제 sum | ||
| */ | ||
|
|
||
| Arrays.sort(nums); | ||
| int n = nums.length; | ||
| int answer = 0; | ||
| int i = 0; | ||
|
|
||
| for(i = 0; i < n; i++) { | ||
| if(nums[i] != i) { | ||
| answer = i; | ||
| return answer; | ||
| } | ||
| } | ||
| if(i == n) { | ||
| answer = n; | ||
| return answer; | ||
| } | ||
| return answer; | ||
| } | ||
| } |
|
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,61 @@ | ||
| /** | ||
| * Definition for singly-linked list. | ||
| * public class ListNode { | ||
| * int val; | ||
| * ListNode next; | ||
| * ListNode() {} | ||
| * ListNode(int val) { this.val = val; } | ||
| * ListNode(int val, ListNode next) { this.val = val; this.next = next; } | ||
| * } | ||
| */ | ||
| class Solution { | ||
| public void reorderList(ListNode head) { | ||
| /** | ||
| 1.Reorder linekd list from 0, n, 1, n-1, ... | ||
| 2.solution: | ||
| - 중간을 반으로 쪼개고,앞/뒤 리스트를 번갈아가면서 연결 | ||
| - step 1) 중간 노드 찾기 | ||
| - step 2) 뒤 리스트 reverse | ||
| - step 3) 두 리스트 merge | ||
| time: O(n), space: O(1) | ||
| */ | ||
|
|
||
| ListNode slow = head; | ||
| ListNode fast = head; | ||
|
|
||
| while(fast != null && fast.next != null) { | ||
| slow = slow.next; | ||
| fast = fast.next.next; | ||
| } | ||
|
|
||
| ListNode second = slow.next; | ||
| slow.next = null; | ||
|
|
||
| ListNode prev = null; | ||
| ListNode curr = second; | ||
|
|
||
| //reverse second linked list | ||
| while(curr != null) { | ||
| ListNode next = curr.next; | ||
| curr.next = prev; | ||
| prev = curr; | ||
| curr = next; | ||
| } | ||
|
|
||
| //merge two linked list | ||
| ListNode first = head; | ||
| LintNode secondHalf = prev; | ||
|
|
||
| while(secondHalf != null) { | ||
| ListNode next1 = first.next; | ||
| ListNode next2 = secondHalf.next; | ||
|
|
||
| next1.next = secondHalf | ||
| secondHalf.next = next1; | ||
|
|
||
| first = next1; | ||
| secondHalf = next2; | ||
| } | ||
|
|
||
| } | ||
| } |
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.
🏷️ 알고리즘 패턴 분석
📊 시간/공간 복잡도 분석
피드백: 각 노드에서 왼쪽, 오른쪽 서브트리의 최대값을 계산하고, 이를 이용해 전체 최대값을 갱신하는 방식으로, 노드 방문은 한 번씩 이루어지며, 재귀 호출 스택은 트리의 높이만큼 사용됩니다.
개선 제안: 현재 구현이 적절해 보입니다.