78. Counting Bits

  1. 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(nsizeof(int)) 的算法
但本题要求时间复杂度 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]+1
其中 dis=im(m(1<<max(res[i]),m=2p,2p+1>=i>=2p)

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;

    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值