leetcode刷题,总结,记录,备忘 338

来源:互联网 发布:人工智能加医疗概念股 编辑:程序博客网 时间:2024/06/13 01:45

leetcode338Counting Bits

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.
我们可以知道,在2进制的表现形式中,2的次幂的数只有1位为1,以这个前提为起点,可以得到动态规划的递推公式 result[i] = result[i % root] + 1;root为当前循环进行到的2的次幂,在每次循环到2的次幂的时候,进行相应的更新,i % root获取去除当前2的指数次幂的数之后的数字的含有1的个数,然后再加上1,因为又加上了一个2的指数次幂,所以要+1。比如result[1] = 1; result[3] = result[3 % 2] + 1,即result[1] + 1;在result[1]的基础上,因为又多了一个2的1次幂2,所以再加一个1.

class Solution {public:    vector<int> countBits(int num) {        vector<int> result;        result.push_back(0);        if (num == 0)        {            return result;        }        result.push_back(1);        if (num == 1)        {            return result;        }                int root = 1;        for (int i = 2; i <= num; ++i)        {            if (i == 2*root)            {                result.push_back(1);                root *= 2;            }            else            {                result.push_back(result[i % root] + 1);            }        }                return result;    }};


0 0