Go, Vantage point
가까운 곳을 걷지 않고 서는 먼 곳을 갈 수 없다.
Github | https://github.com/overnew/
Blog | https://everenew.tistory.com/
티스토리 뷰
반응형
문제
https://leetcode.com/problems/counting-bits/
Counting Bits - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
풀이
난이도: Easy

위의 그림을 보면 알겠지만
2^k ~ 2^(k+1) -1 의 수들은 k+1 번째 비트가 1이고 나머지는 0 ~ 2^k -1와 뒷부분이 완전히 동일하다.
따라서 0 ~ 2^k -1의 비트에서 1의 수들에 + 1을 붙인 것이 2^k ~ 2^(k+1) -1의 1의 개수가 된다.
따라서 계산해 둔 수들을 이용하면 선형 탐색으로 O(n)의 시간복잡도에 답을 구할 수 있다.
비트 연산에 중점을 두어 푼다면 다음과 같이 >>연산자로 더 깔끔히 구현이 가능하다.
1
2
3
4
5
6
7
|
vector<int> countBits(int num) {
vector<int> res(num + 1, 0);
for (int i = 1; i <= num; ++i) {
res[i] = res[i >> 1] + (i & 1);
}
return res;
}
|
cs |
코드 출처: Four lines, C++, time O(n), space O(n)
코드
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public: | |
vector<int> countBits(int n) { | |
vector<int> dp(n+1); | |
dp[0] = 0; | |
//복사할 배열의 길이 | |
int copy_len = 1, next_idx; | |
for (; copy_len <= n; copy_len *= 2) { | |
for (int idx = 0; idx < copy_len ; ++idx ) { | |
next_idx = idx + copy_len; | |
if (next_idx > n) | |
break; | |
dp[idx + copy_len] = 1 + dp[idx]; | |
} | |
} | |
return dp; | |
} | |
}; |
반응형
'알고리즘 공부 > LeetCode' 카테고리의 다른 글
[LeetCode] 322. Coin Change (C++) (0) | 2021.10.21 |
---|---|
[LeetCode] 268. Missing Number (C++) (0) | 2021.10.20 |
[LeetCode] 371. Sum of Two Integers (C++) (0) | 2021.10.18 |
[LeetCode] 11. Container With Most Water (C++) (0) | 2021.10.15 |
[LeetCode] 15. 3Sum (C++) (0) | 2021.10.13 |
댓글