您的位置:首页 > 其它

78. Counting Bits

2016-05-22 11:24 253 查看
Counting Bits My Submissions QuestionEditorial Solution

Total Accepted: 22588 Total Submissions: 40178 Difficulty: Medium

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:

For num = 5 you should return [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到num的所有对应整数的二进制位数

本身不难,你可以很直接就想到O(n∗sizeof(int))O(n*sizeof(int))的算法

但本题要求时间复杂度O(n)O(n)

所以必须要考虑用到前面的结果来求解,不然不可能

先观察下

0 | 0 0 0 0

1 | 0 0 0 1

2 | 0 0 1 0

3 | 0 0 1 1

4 | 0 1 0 0

5 | 0 1 0 1

6 | 0 1 1 0

7 | 0 1 1 1

8 | 1 1 0 0

9 | 1 1 0 1

10 | 1 1 1 0

11 | 1 1 1 1

观察可以知道,其实在2的整数次幂的时候,后面的0或者1其实前面都出现过,比如4-7中任一个数除了第三位是1,后面2位是0-3依次排列,就是利用4-7中的某数离4的距离来确定用到的是0-3的哪个数,

这样:res[i]=res[dis]+1res[i] = res[dis]+1

其中dis=i−m(m为(1<<max(res[i]),或者理解成m=2p,2p+1>=i>=2p)dis=i-m(m为(1<=i>=2^p)

class Solution {
public:
vector<int> countBits(int num) {
assert(num>=0);
vector<int> res(num+1);
res[0]=0;
if(num==0)return res;
int max = 0;
for(int i=1;i<=num;++i){
int dis = i-(1<<max);
res[i]=res[dis]+1;
if(max<res[i])max = res[i];
}
return res;

}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: