diff --git a/course-schedule/moonjonghoo.js b/course-schedule/moonjonghoo.js new file mode 100644 index 000000000..703a36294 --- /dev/null +++ b/course-schedule/moonjonghoo.js @@ -0,0 +1,31 @@ +var canFinish = function (numCourses, prerequisites) { + const graph = Array.from({ length: numCourses }, () => []); + const inDegree = Array(numCourses).fill(0); + + // 그래프 만들기 및 진입 차수 계산 + for (const [course, pre] of prerequisites) { + graph[pre].push(course); + inDegree[course]++; + } + + // 진입 차수가 0인 노드부터 시작 + const queue = []; + for (let i = 0; i < numCourses; i++) { + if (inDegree[i] === 0) queue.push(i); + } + + let count = 0; + while (queue.length) { + const node = queue.shift(); + count++; + + for (const neighbor of graph[node]) { + inDegree[neighbor]--; + if (inDegree[neighbor] === 0) { + queue.push(neighbor); + } + } + } + + return count === numCourses; +}; diff --git a/invert-binary-tree/moonjonghoo.js b/invert-binary-tree/moonjonghoo.js new file mode 100644 index 000000000..bee133d89 --- /dev/null +++ b/invert-binary-tree/moonjonghoo.js @@ -0,0 +1,17 @@ +var invertTree = function (root) { + if (root === null) return null; + + let queue = [root]; + + while (queue.length > 0) { + let node = queue.shift(); + + // 왼쪽과 오른쪽 자식을 교환 + [node.left, node.right] = [node.right, node.left]; + + if (node.left) queue.push(node.left); + if (node.right) queue.push(node.right); + } + + return root; +}; diff --git a/jump-game/moonjonghoo.js b/jump-game/moonjonghoo.js new file mode 100644 index 000000000..a6799612e --- /dev/null +++ b/jump-game/moonjonghoo.js @@ -0,0 +1,10 @@ +var canJump = function (nums) { + let maxReach = 0; + + for (let i = 0; i < nums.length; i++) { + if (i > maxReach) return false; + maxReach = Math.max(maxReach, i + nums[i]); + } + + return true; +}; diff --git a/search-in-rotated-sorted-array/moonjonghoo.js b/search-in-rotated-sorted-array/moonjonghoo.js new file mode 100644 index 000000000..36e3c2e50 --- /dev/null +++ b/search-in-rotated-sorted-array/moonjonghoo.js @@ -0,0 +1,29 @@ +var search = function (nums, target) { + let left = 0, + right = nums.length - 1; + + while (left <= right) { + const mid = Math.floor((left + right) / 2); + + if (nums[mid] === target) return mid; + + // 왼쪽 절반이 정렬되어 있는 경우 + if (nums[left] <= nums[mid]) { + if (nums[left] <= target && target < nums[mid]) { + right = mid - 1; // 왼쪽 범위로 이동 + } else { + left = mid + 1; // 오른쪽 범위로 이동 + } + } + // 오른쪽 절반이 정렬되어 있는 경우 + else { + if (nums[mid] < target && target <= nums[right]) { + left = mid + 1; // 오른쪽 범위로 이동 + } else { + right = mid - 1; // 왼쪽 범위로 이동 + } + } + } + + return -1; +};