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

[강희찬] WEEK 10 Solution #532

Merged
merged 7 commits into from
Oct 18, 2024
Merged
Show file tree
Hide file tree
Changes from 5 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
34 changes: 34 additions & 0 deletions course-schedule/HC-kang.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
/**
* https://leetcode.com/problems/course-schedule/
* T.C. O(V + E)
* S.C. O(V + E)
*/
function canFinish(numCourses: number, prerequisites: number[][]): boolean {
const graph: number[][] = Array.from({ length: numCourses }, () => []);
for (const [course, pre] of prerequisites) {
graph[pre].push(course);
}

const visited = new Array(numCourses).fill(false);
const visiting = new Array(numCourses).fill(false);

const dfs = (course: number): boolean => {
if (visited[course]) return true;
if (visiting[course]) return false;

visiting[course] = true;
for (const neighbor of graph[course]) {
if (!dfs(neighbor)) return false;
}
visiting[course] = false;
visited[course] = true;

return true;
};

for (let i = 0; i < numCourses; i++) {
if (!visited[i] && !dfs(i)) return false;
}

return true;
}
48 changes: 48 additions & 0 deletions invert-binary-tree/HC-kang.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
// class TreeNode {
// val: number;
// left: TreeNode | null;
// right: TreeNode | null;
// constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
// this.val = val === undefined ? 0 : val;
// this.left = left === undefined ? null : left;
// this.right = right === undefined ? null : right;
// }
// }

/**
* https://leetcode.com/problems/invert-binary-tree
* T.C. O(n)
* S.C. O(n)
Copy link
Contributor

Choose a reason for hiding this comment

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

재귀호출 스택의 깊이는 트리의 높이에 비례하여 증가하니까 공간 복잡도를 O(N)으로 표기하는 것보다는 O(H)로 표현하는 것이 좀 더 적절할 것 같다는 생각입니다

Copy link
Contributor Author

Choose a reason for hiding this comment

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

@obzva 안녕하세요 플린님 요즘 잘 지내시죠?
말씀주신 내용도 맞다고 생각합니다!
하지만 최악의 경우, 그러니까 n개의 노드가 극단적으로 치우친 경우, 결국 h=n이 되므로 O(n)으로 작성하였습니다

Copy link
Contributor

Choose a reason for hiding this comment

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

네 ㅎㅎ 희찬님도 잘 지내시죠?

*/
function invertTree(root: TreeNode | null): TreeNode | null {
if (root === null) {
return null;
}

[root.left, root.right] = [root.right, root.left];
invertTree(root.left);
invertTree(root.right);

return root;
}

/**
* T.C. O(n)
* S.C. O(n)
*/
function invertTree(root: TreeNode | null): TreeNode | null {
const stack: Array<TreeNode | null> = [root];

while (stack.length > 0) {
const node = stack.pop()!;

if (node === null) {
continue;
}

[node.left, node.right] = [node.right, node.left];
stack.push(node.left, node.right);
}

return root;
}
16 changes: 16 additions & 0 deletions jump-game/HC-kang.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
/**
* https://leetcode.com/problems/jump-game/
* T.C. O(n)
* S.C. O(1)
*/
function canJump(nums: number[]): boolean {
let max = 0;

for (let i = 0; i < nums.length; i++) {
if (i > max) return false;
max = Math.max(max, i + nums[i]);
if (max >= nums.length - 1) return true;
}

return false;
}
32 changes: 32 additions & 0 deletions search-in-rotated-sorted-array/HC-kang.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
/**
* https://leetcode.com/problems/search-in-rotated-sorted-array
* T.C. O(log n)
* S.C. O(1)
*/
function search(nums: number[], target: number): number {
let left = 0;
let right = nums.length - 1;

while (left <= right) {
let mid = left + ((right - left) >> 1);
Copy link
Contributor

Choose a reason for hiding this comment

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

JS/TS 에서는 정수 나눗셈 연산을 이렇게 구현할 수 있군요 :)

Copy link
Contributor Author

Choose a reason for hiding this comment

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

저도 이전에는 (left + right) / 2 로 하다가, 최근에 오버플로우도 막고 좀더 있어보이는(?) 방법이라고 해서 따라해봤습니다.

그런데 확인해보니 JS에서는 그냥 Math.floor((left + right) / 2) 쓰는게 낫다고 하네요 ㅋㅋ

Copy link
Contributor

Choose a reason for hiding this comment

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

어떤 이유에서 Math.floor가 더 나은가요?

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. JS 엔진 내부적으로 이미 성능 최적화가 되어서 속도 차이도 별로 나지 않고, 오히려 가독성을 해친다
  2. 부동 소수점을 사용해서, 정밀도가 손실 될지언정 오버플로는 발생하지 않음

요 두개로 기억합니다!
정밀도도 10^15 가까이 큰 수를 다루는게 아니라면 큰 문제가 없었구요


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;
}