338. Counting Bits

来源:互联网 发布:情义我心知 电影 2005 编辑:程序博客网 时间:2024/06/06 20:17

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.
题目的要求是给定一个整数num,在0<=i<=num的范围内,求每个整数的二进制表示中1的个数,并以数组的形式返回结果。这道题目按照正常的解题思路去解决非常简单,但是复杂度不够理想,题目希望我们可以相处复杂度为O(n)的解法。
既然通过O(n)的算法可以解决,那么必然存在某种规律性:
数字     二进制    1的个数0        0000      01        0001      12        0010      13        0011      24        0100      15        0101      26        0110      27        0111      38        1000      1

有一个显然的事实就是,只要是2的指数,1的个数都是1。至于其他数字,我们可以发现,每个数字1的个数,都是数字i&(i-1)中1的个数加1。
所以,代码为:
class Solution {public:    vector<int> countBits(int num) {        vector<int> result(num+1, 0);        for (int i = 1; i <= num; i++) {            result[i] = result[i&(i-1)] + 1;        }        return result;    }};


原创粉丝点击