Skip to content

Commit

Permalink
update post
Browse files Browse the repository at this point in the history
  • Loading branch information
dev-jonghoonpark committed May 26, 2024
1 parent 0f82241 commit 34f2189
Showing 1 changed file with 76 additions and 1 deletion.
77 changes: 76 additions & 1 deletion _posts/2024-04-23-leetcode-338.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,21 @@
layout: post
title: (Leetcode) 338 - Counting Bits
categories: [스터디-알고리즘]
tags: [자바, java, 스트림, stream, 리트코드, Leetcode, 알고리즘, algorithm]
tags:
[
자바,
java,
스트림,
stream,
리트코드,
Leetcode,
알고리즘,
algorithm,
array,
bit,
dp,
dynamic programming,
]
date: 2024-04-23 20:30:00 +0900
---

Expand Down Expand Up @@ -58,3 +72,64 @@ num 이 0 보다 클경우 shift를 이용하여 1인지 확인하고 1일 경
## TC, SC

두 풀이의 시간 복잡도는 O(n \* log n)이고, 공간 복잡도는 O(n)이다. n \* log n 인 이유는 bit의 수는 log 를 따르게 되기 때문이다.

## dp로 풀어보기

```java
public int[] countBits(int n) {
int result[] = new int[n + 1];
for (int i = 1; i <= n; i++) {
result[i] = result[i >> 1] + (i & 1);
}
return result;
}
```

1씩 증가함에 따라 비트는 다음과 같이 진행이 된다.

0 = 0000
1 = 0001
2 = 0010
3 = 0011
4 = 0100
5 = 0101
6 = 0110
7 = 0111
...

마지막 bit가 0이 되었다가 1이 되는 것을 반복한다. 이 성질을 이요하면서 이전의 결과값을 이용하면서 마지막 비트의 변화를 관찰한다.

- result[0] = 0
- result[1]
- result[1 >> 1] = result[0] = 0
- (0001 & 1) = 1
- 0 + 1 = 1
- result[2]
- result[2 >> 1] = result[1] = 1
- (0010 & 1) = 0
- 1 + 0 = 1
- result[3]
- result[3 >> 1] = result[1] = 1
- (0011 & 1) = 1
- 1 + 1 = 2
- result[4]
- result[4 >> 1] = result[2] = 1
- (0100 & 1) = 0
- 1 + 0 = 1
- result[5]
- result[5 >> 1] = result[2] = 1
- (0101 & 1) = 1
- 1 + 1 = 1
- result[6]
- result[6 >> 1] = result[3] = 2
- (0110 & 1) = 0
- 2 + 0 = 2
- result[7]
- result[7 >> 1] = result[3] = 2
- (0111 & 1) = 1
- 2 + 1 = 3
- ...

## TC, SC

두 풀이의 시간 복잡도는 O(n)이고, 공간 복잡도는 O(n)이다.

0 comments on commit 34f2189

Please sign in to comment.