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

[선재] Week14 #597

Merged
merged 3 commits into from
Nov 17, 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
31 changes: 31 additions & 0 deletions binary-tree-level-order-traversal/sunjae95.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
/**
* @description
* 동일한 depth를 방문해야하므로 bfs 및 트리 순회
*
* n = length of node of root
* time complexity: O(n)
* space complexity: O(n)
*/
var levelOrder = function (root) {
if (!root) return [];

const answer = [];
const queue = [root];
let queueCurrentIndex = 0;

while (queue.length > queueCurrentIndex) {
answer.push([]);
const answerLastIndex = answer.length - 1;
const depthEndIndex = queue.length;

while (depthEndIndex !== queueCurrentIndex) {
const tree = queue[queueCurrentIndex++];

answer[answerLastIndex].push(tree.val);
if (tree.left) queue.push(tree.left);
if (tree.right) queue.push(tree.right);
}
}

return answer;
};
31 changes: 31 additions & 0 deletions house-robber-ii/sunjae95.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
/**
* @description
* 점화식: dp[i] = Math.max(dp[i - 1], dp[i - 2] + current);
* 순회한다는 조건이 있으므로 다음과 같이 분기처리 할 수 있다.
* 1. 처음이 선택 O 마지막 X
* 2. 처음이 선택 X 마지막 상관없음
*
* n = length of nums
* time complexity: O(n)
* space complexity: O(n)
*/
var rob = function (nums) {
if (nums.length === 1) return nums[0];
if (nums.length === 2) return Math.max(nums[0], nums[1]);

const hasFirst = Array.from({ length: nums.length }, (_, i) =>
i < 2 ? nums[0] : 0
);
const noFirst = Array.from({ length: nums.length }, (_, i) =>
i === 1 ? nums[i] : 0
);
for (let i = 2; i < nums.length; i++) {
hasFirst[i] = Math.max(hasFirst[i - 1], hasFirst[i - 2] + nums[i]);
noFirst[i] = Math.max(noFirst[i - 1], noFirst[i - 2] + nums[i]);
if (i === nums.length - 1) {
hasFirst[i] = Math.max(hasFirst[i - 1], hasFirst[i - 2]);
}
}

return Math.max(hasFirst[nums.length - 1], noFirst[nums.length - 1]);
};
18 changes: 18 additions & 0 deletions reverse-bits/sunjae95.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
/**
* @description
*
* n = length of n
* time complexity: O(n)
* space complexity: O(n)
*/
var reverseBits = function (n) {
let answer = 0;
let binary = n.toString(2);

if (binary.length < 32) binary = "0".repeat(32 - binary.length) + binary;

for (let i = binary.length - 1; i >= 0; i--)
answer += Math.pow(2, i) * Number(binary[i]);

return answer;
};