Skip to content
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
82 changes: 82 additions & 0 deletions binary-tree-level-order-traversal/rivkode.java
Copy link
Contributor

Choose a reason for hiding this comment

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

제가 문제를 안 읽어서... poll, offer라는 함수를 쓰는 걸 처음 봤네요. 반환, 추가의 역할을 하나요?

Copy link
Member Author

Choose a reason for hiding this comment

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

네 맞아요 poll은 Queue 자료구조에서 가장 첫번째로 들어온 요소를 반환하고 Queue에서 제거합니다. offer은 가장 마지막에 추가하는 역할을 합니다

Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
/*
BFS를 사용한 이유는 depth 가 기준이 되어야 하기 때문이다.
depth 별로 value값을 넣어야하기 때문에 BFS로 탐색하며 해당하는 모든 값들을 List에 넣어주었다.
이때 포인트는 몇개의 값들을 depth 별로 나눌것인가 ? 인데 왜냐하면 queue는 자식 노드들을 탐색하며 지속적으로 추가되기 때문이다.
그래서 2중으로 loop를 돌아야 한다.
첫번째는 while문으로 queue가 empty될때까지 확인하는 loop이고
두번째는 queue 사이즈를 미리 계산하여 특정 level의 개수 만큼 도는 for loop 이다.
이렇게 2번 loop를 돌면 depth 별로 size를 알 수 있게된다.
*/

/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
import java.util.*;

class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
Queue<TreeNode> queue = new LinkedList<>();
List<List<Integer>> result = new ArrayList<>();

if (root == null) {
return new ArrayList<>();
}

queue.offer(root);

while(!queue.isEmpty()) {
List<Integer> levelList = new ArrayList<>();
int queueSize = queue.size();

for (int i=0; i<queueSize; i++) {
TreeNode node = queue.poll();
if (node == null) {
continue;
}

levelList.add(node.val);

if (node.left != null) {
queue.offer(node.left);
}

if (node.right != null) {
queue.offer(node.right);
}
}
result.add(levelList);
}

return result;
}

public class TreeNode {
int val;
TreeNode left;
TreeNode right;

TreeNode() {}
TreeNode(int val) { this.val = val; }
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
}




27 changes: 27 additions & 0 deletions counting-bits/rivkode.java
Copy link
Contributor

Choose a reason for hiding this comment

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

자바에 toBinaryString 같은 함수가 존재하는지 몰랐네요!

Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
/*
입력받은 n에 대해 toBinaryString() 을 사용하여 binaryString 값을 알아낸뒤 charAt()으로 각 인덱스별 접근하여 1의 개수를 찾아내는 방식이다.
*/

class Solution {
public int[] countBits(int n) {
int[] answer = new int[n + 1];
for (int i=0; i<n+1; i++) {
String bit = Integer.toBinaryString(i);
System.out.println(bit);
int cnt = 0;
for (int j=0; j < bit.length(); j++) {
char c = bit.charAt(j);
int num = c-'0';
Copy link
Contributor

Choose a reason for hiding this comment

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

이 코드가 어떤 역할을 하는 건지 궁금해요. 무작정 2로 나눠서 몫과 나머지를 통해 답을 도출한다는 생각만 했더니...

Copy link
Member Author

Choose a reason for hiding this comment

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

안녕하세요 ㅎㅎ 아스키 코드를 사용하였습니다. 여기서 char c 는 숫자형태의 char 를 기대하고 있습니다. 그러므로 '0' 을 빼주게 되면 십진법의 Int 숫자가 반환되게 됩니다. 사실 십진법에 해당하는 48을 빼주어도 되는데 '0' 을 빼주는게 더 직관적이라 보통 숫자연산을 할때 저는 '0' 을 빼줍니다. 그러면 원하는 숫자 int 값을 얻을 수 있게 되어서요.

if (num == 1) {
cnt += 1;
}
}

answer[i] = cnt;
}

return answer;
}
}


87 changes: 87 additions & 0 deletions house-robber-ii/rivkode.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
/*
dp를 사용 dp를 사용하는 이유는 dfs를 할 경우 시간초과가 나므로
그리고 i번째의 최대값을 찾는 문제는 점화식으로 표현이 가능하므로 점화식으로 나타낼 수 있으면 dp도 활용이 가능하다.
앞으로 반복되는 문제가 있으면 dp를 적극 활용해보자.

각 dp 배열들의 1번째 집에 대해 초기화를 해주고 for 루프의 i=2부터 시작하는게 포인트였다.
nums[i]로 접근했을때 IndexOutOfRange에러가 발생하는게 아닌가 싶었지만 2부터 시작해서 최대값이 i는 배열-1 까지다.

dp1은 첫번째집을 방문했을때, dp2는 두번째집을 방문했을때이며 dp1은 마지막집을 방문하지 못한다.
이 조건을 i가 nums.length보다 작을 경우로 판단한다.

최종 최댓값은 각 dp 배열의 마지막 그리고 마지막에서 2번째에 저장되어있으므로 nums배열 크기 - 1, -2 한 값으로 조회한다.
*/


import java.util.*;

class Solution {
public int rob(int[] nums) {
int[] dp1 = new int[nums.length];
int[] dp2 = new int[nums.length];

if (nums.length == 1) {
return nums[0];
}

dp1[0] = dp1[1] = nums[0];
dp2[1] = nums[1];

for (int i=2; i<nums.length; i++) {
if (i < nums.length) {
dp1[i] = Math.max((nums[i] + dp1[i-2]), dp1[i-1]);
}
dp2[i] = Math.max((nums[i] + dp2[i-2]), dp2[i-1]);
}

return Math.max(dp1[nums.length -2], dp2[nums.length -1]);
}
}




// 아래는 dfs 로 푼 방식
// import java.util.*;

// class Solution {
// public int rob(int[] nums) {
// if (nums == null || nums.length == 0) {
// return 0;
// }

// if (nums.length == 1) {
// return nums[0];
// }

// return Math.max(
// nums[0] + dfs(nums, 2, true), dfs(nums,1,false)
// );

// }

// public int dfs(int[] nums, int idx, boolean first) {
// // idx가 nums의 길이와 같거나 크다는 것은 범위를 초과했다는 의미이므로 0 return
// if (idx >= nums.length) {
// return 0;
// }

// // idx가 nums의 끝에 도달했을 경우 first의 여부에 따라 결과값이 바뀐다.
// if (idx == nums.length - 1) {
// // 첫번째를 방문시 마지막은 사용불가
// if (first) {
// return 0;
// } else {
// return nums[nums.length - 1];
// }
// }

// // 현재 집을 털었을때 현재 idx의 값과 다음 집을 턴 최대값
// int curRob = nums[idx] + dfs(nums, idx + 2, first);
// // 현재 집을 건너뛸때 다음 idx의 값으로 다음 집을 턴 최대값
// int nextRob = dfs(nums, idx + 1, first);

// return Math.max(curRob, nextRob);
// }
// }