LeetCode解题报告 338. Counting Bits [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.

Hint:

  1. You should make use of what you have produced already.
  2. Divide the numbers in ranges like [2-3], [4-7], [8-15] and so on. And try to generate new range from previous.
  3. Or does the odd/even status of the number help you in calculating the number of 1s?

解题思路

题目意思就是将从0到给定的num的所有数字进行二进制表示后,计算每一个数字的二进制表示有多少个1,并输出成一个数组。同时提示不能用最无脑的办法算,要求O(n)的时间和空间复杂度。
在 hint提示中,有说划分成[2,3],[4,7][8,15]来找规律,列出表格如下:



可以看到,个数在上述三个区间内分别是12,1223,12232334。
比较容易发现奇数数字1的个数都是之前一个偶数数字1的个数加一,那么再继续寻找偶数数字和之前的数字有什么关系,题目中也提示使用之前已经计算出来的数字。
在二进制的最后一位加一个0,就相当于把这个数字乘2倍,类似十进制的末位加一个0,就是把这个数字乘10倍一样。
所以说,某个偶数数字和它的1/2大小的数字的二进制形式上就是末位多了一个0,那么1的个数是一样的。如6和3,14和7等。因此,用n/2的‘1’个数的结果来表示n的结果。

时间复杂度为O(n)

代码如下:
class Solution {
public:
    vector<int> countBits(int num) {
        vector<int>result(num+1,0);
        for (int i=1; i<=num; i++) {
            if (i%2==0) {
                result[i]=result[i/2];
            }
            else{
                result[i]=result[i-1]+1;
            }
        }
        return result;
    }
};

Run Time Language
27 minutes ago Counting Bits Accepted 63 ms
运行时间>80%多的其他cpp

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值