Skip to content

Commit 145a5b0

Browse files
authored
Merge pull request #597 from Sunjae95/main
[선재] Week14
2 parents fad730e + 08706ec commit 145a5b0

File tree

3 files changed

+80
-0
lines changed

3 files changed

+80
-0
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
/**
2+
* @description
3+
* 동일한 depth를 방문해야하므로 bfs 및 트리 순회
4+
*
5+
* n = length of node of root
6+
* time complexity: O(n)
7+
* space complexity: O(n)
8+
*/
9+
var levelOrder = function (root) {
10+
if (!root) return [];
11+
12+
const answer = [];
13+
const queue = [root];
14+
let queueCurrentIndex = 0;
15+
16+
while (queue.length > queueCurrentIndex) {
17+
answer.push([]);
18+
const answerLastIndex = answer.length - 1;
19+
const depthEndIndex = queue.length;
20+
21+
while (depthEndIndex !== queueCurrentIndex) {
22+
const tree = queue[queueCurrentIndex++];
23+
24+
answer[answerLastIndex].push(tree.val);
25+
if (tree.left) queue.push(tree.left);
26+
if (tree.right) queue.push(tree.right);
27+
}
28+
}
29+
30+
return answer;
31+
};

house-robber-ii/sunjae95.js

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
/**
2+
* @description
3+
* 점화식: dp[i] = Math.max(dp[i - 1], dp[i - 2] + current);
4+
* 순회한다는 조건이 있으므로 다음과 같이 분기처리 할 수 있다.
5+
* 1. 처음이 선택 O 마지막 X
6+
* 2. 처음이 선택 X 마지막 상관없음
7+
*
8+
* n = length of nums
9+
* time complexity: O(n)
10+
* space complexity: O(n)
11+
*/
12+
var rob = function (nums) {
13+
if (nums.length === 1) return nums[0];
14+
if (nums.length === 2) return Math.max(nums[0], nums[1]);
15+
16+
const hasFirst = Array.from({ length: nums.length }, (_, i) =>
17+
i < 2 ? nums[0] : 0
18+
);
19+
const noFirst = Array.from({ length: nums.length }, (_, i) =>
20+
i === 1 ? nums[i] : 0
21+
);
22+
for (let i = 2; i < nums.length; i++) {
23+
hasFirst[i] = Math.max(hasFirst[i - 1], hasFirst[i - 2] + nums[i]);
24+
noFirst[i] = Math.max(noFirst[i - 1], noFirst[i - 2] + nums[i]);
25+
if (i === nums.length - 1) {
26+
hasFirst[i] = Math.max(hasFirst[i - 1], hasFirst[i - 2]);
27+
}
28+
}
29+
30+
return Math.max(hasFirst[nums.length - 1], noFirst[nums.length - 1]);
31+
};

reverse-bits/sunjae95.js

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
/**
2+
* @description
3+
*
4+
* n = length of n
5+
* time complexity: O(n)
6+
* space complexity: O(n)
7+
*/
8+
var reverseBits = function (n) {
9+
let answer = 0;
10+
let binary = n.toString(2);
11+
12+
if (binary.length < 32) binary = "0".repeat(32 - binary.length) + binary;
13+
14+
for (let i = binary.length - 1; i >= 0; i--)
15+
answer += Math.pow(2, i) * Number(binary[i]);
16+
17+
return answer;
18+
};

0 commit comments

Comments
 (0)