Skip to content
Open
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
32 changes: 31 additions & 1 deletion counting-bits/juhui-jeong.java
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🏷️ 알고리즘 패턴 분석

  • 패턴: Dynamic Programming
  • 설명: 이 코드는 이전 값들을 이용하여 현재 숫자의 1비트 개수를 계산하는 방식으로, DP의 점화식을 활용하는 패턴에 속합니다. 효율성을 위해 결과를 저장하고 재사용하는 특징이 있습니다.

📊 시간/공간 복잡도 분석

복잡도
Time O(n log n)
Space O(n)

피드백: 첫 번째 방법은 각 수를 이진수로 변환하는 과정이 O(log n)이고, 이를 n번 수행하므로 O(n log n). 두 번째 방법은 재귀 호출로 각 수를 2로 나누며 계산하는데, 최악의 경우 O(log n) 호출이 발생하며 n개 수에 대해 수행하므로 전체적으로 O(n log n).

개선 제안: 현재 구현이 적절해 보입니다.

💡 풀이에 시간/공간 복잡도를 주석으로 남겨보세요!

Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@


/*
이전 풀이
class Solution {
public int[] countBits(int n) {
ArrayList<Integer> list = new ArrayList<>();
Expand All @@ -22,3 +23,32 @@ public int[] countBits(int n) {
return ans;
}
}
*/
/*
시간 복잡도: O(n log n)
공간 복잡도: O(n)
*/
class Solution {
public int[] countBits(int n) {
// 0부터 n까지의 이진수를 만든다.
// 이진수로 변환된 수에서 1의 갯수를 카운팅한다.
// 0부터 n까지 1의 갯수를 카운팅한 것을 배열로 만들어 반환한다. 이때 배열의 길이는 n+1.
int[] result = new int[n+1];

for (int i = 0; i <= n; i++) {
int num = divideTwo(i, 0);
result[i] = num;
}
return result;
}

private int divideTwo(int n, int remainderCnt) {
int divideNum = n/2;
int remainder = n%2;

int calcualteReminderNum = remainder + remainderCnt;
if (divideNum == 0) return calcualteReminderNum;

return divideTwo(divideNum, calcualteReminderNum);
}
}
Loading