2020年6月13日
LeetCode 338. Counting Bits
C++, LeetCode, 算法, 编程
0 Comments
Given a non negative integer number num. For every numbers i in the range 0 ≤ i ≤ num calculate the number of 1’s in their binary representation and return them as an array.
Example 1:
Input: 2 Output: [0,1,1]
Example 2:
Input: 5 Output: [0,1,1,2,1,2]
Follow up:
- It is very easy to come up with a solution with run time O(n*sizeof(integer)). But can you do it in linear time O(n) /possibly in a single pass?
- Space complexity should be O(n).
- Can you do it like a boss? Do it without using any builtin function like __builtin_popcount in c++ or in any other language.
解析:根据给定的整数,对于 0 ≤ i ≤ num 范围中的每个数字 i ,计算其二进制数中的 1 的数目并将它们作为数组返回。
思路:首先想到的是遍历每一个数值,然后计算当前数字中包含1的个数。这里要求空间复杂度和时间复杂度均为O(N),争取一次遍历即可获取结果。因此考虑动态规划的思路,计算当前数字结果时尽量用到之前的结果,分析二进制数值的特点,发现如果当前数字i是偶数,则i是由i/2左移得到的,所以i包含1的个数与i/2中1的个数相同;如果i是奇数,则在i-1基础上增加1.具体代码如下:
class Solution {
public:
vector<int> countBits(int num) {
vector<int> result(num+1, 0);
if(num == 0)
return result;
result[1] = 1;
for(int i = 2; i <= num; i++)
{
if(i % 2 == 0)
result[i] = result[i/2];
else
result[i] = result[i-1] + 1;
}
return result;
}
};