Skip to content
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

[Tony] WEEK 10 Solutions #534

Merged
merged 5 commits into from
Oct 18, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions course-schedule/TonyKim9401.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
// TC: O(n + p)
// n -> number of courses, p -> the length of prerequisites
// SC: O(n + m)
// n -> the length of the graph size, m -> the length of nested list's size
class Solution {
public boolean canFinish(int numCourses, int[][] prerequisites) {
List<List<Integer>> graph = new ArrayList<>();
int[] inDegree = new int[numCourses];

for (int i = 0; i < numCourses; i++) graph.add(new ArrayList<>());

for (int[] prerequisite : prerequisites) {
int course = prerequisite[0];
int pre = prerequisite[1];
graph.get(pre).add(course);
inDegree[course] += 1;
}

Queue<Integer> q = new LinkedList<>();
for (int i = 0; i < numCourses; i++) {
if (inDegree[i] == 0) q.offer(i);
}

int visitedCourses = 0;
while (!q.isEmpty()) {
int course = q.poll();
visitedCourses += 1;

for (int nextCourse : graph.get(course)) {
inDegree[nextCourse] -= 1;
if (inDegree[nextCourse] == 0) q.offer(nextCourse);
}
}

return visitedCourses == numCourses;
}
}
16 changes: 16 additions & 0 deletions invert-binary-tree/TonyKim9401.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
// TC: O(n)
// -> visit all nodes to invert
// SC: O(n)
// -> create all nodes again to exchange
Comment on lines +3 to +4
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

공간복잡도 분석에서 저와 생각이 다르신 것 같습니다
invertTree 함수 내에서 left, right를 선언하여 root.left = right; root.right = left 해주는 일련의 과정을 creating all nodes라고 볼 순 없을 것 같습니다
이 부분은 root.left와 root.right의 레퍼런스만 바꿔주는 것이기 때문에 공간복잡도 고려에 포함되지 않아도 될 것 같다는 생각입니다

이 풀이는 재귀 함수 호출을 이용하고 있으므로 위에서 언급한 부분 대신 재귀 호출 스택을 공간복잡도 고려에 포함시키는게 좋을 것 같습니다.

Copy link
Contributor Author

@TonyKim9401 TonyKim9401 Oct 18, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@obzva 의견 감사합니다! 제가 설명을 오해의 소지를 불러 일으키도록 적어뒀네요!
좋은 분석 너무 감사합니다.
제가 분석한 공간 복잡도의 케이스는 크게 2가지 입니다.
1. 균형 잡힌 트리, 2. 편향된 트리
1. 균형 잡힌 트리 의 경우 재귀호출로 O(log n)만큼 공간을 차지한다고 생각되구요.
2. 편향된 트리 의 경우 모든 트리를 다 조회하고 만들어야 하기 때문에 O(n)의 공간복잡도가 소요될거라 생각합니다.
따라서, 최악의 경우 평향된 트리를 생각했을때 O(n) 의 공간복잡도가 나올 거라 생각됩니다.

class Solution {
public TreeNode invertTree(TreeNode root) {
if (root == null) return null;
invertTree(root.left);
invertTree(root.right);
TreeNode left = root.left;
TreeNode right = root.right;
root.left = right;
root.right = left;
return root;
}
}
13 changes: 13 additions & 0 deletions jump-game/TonyKim9401.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
// TC: O(n)
// SC: O(1)
class Solution {
public boolean canJump(int[] nums) {
int jump = 0;

for (int i = 0; i < nums.length; i++) {
if (i > jump) return false;
jump = Math.max(jump, i + nums[i]);
}
return true;
}
}
30 changes: 30 additions & 0 deletions merge-k-sorted-lists/TonyKim9401.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
// TC: O(n * log m)
// m -> the number of the lists, n -> the number of node
// SC: O(m)
// m -> the number of the lists (max m)
class Solution {
public ListNode mergeKLists(ListNode[] lists) {
if (lists == null || lists.length == 0) return null;

PriorityQueue<ListNode> pq = new PriorityQueue<>((a, b) -> a.val - b.val);

for (ListNode node : lists) {
if (node != null) pq.offer(node);
}

ListNode dummy = new ListNode(0);
ListNode current = dummy;

while (!pq.isEmpty()) {
ListNode minNode = pq.poll();
current.next = minNode;
current = current.next;

if (minNode.next != null) {
pq.offer(minNode.next);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

오.. 우선순위 큐가 정말 좋네요. 신기하고 간단한 풀이네요

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

사실 리스트가 1 ~ n 까지 있으면 1, 2 머지 -> (1,2머지), 3머지 이런식으로 풀었는데 시간이 너무 오래 걸리더라구요..
다른 풀이를 살짝 참고하여 풀었습니다. 덕분에 시간 복잡도가 확 줄었네요!

}
}

return dummy.next;
}
}
25 changes: 25 additions & 0 deletions search-in-rotated-sorted-array/TonyKim9401.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
// TC: O(log n)
// -> binary search
// SC: O(1)
class Solution {
public int search(int[] nums, int target) {

int start = 0;
int end = nums.length - 1;

while (start <= end) {
int mid = start + (end - start) / 2;

if (nums[mid] == target) return mid;

if (nums[start] <= nums[mid]) {
if (nums[start] <= target && target < nums[mid]) end = mid - 1;
else start = mid + 1;
} else {
if (nums[mid] < target && target <= nums[end]) start = mid + 1;
else end = mid - 1;
}
}
return -1;
}
}