题目要求

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.

思路和代码

这里除了暴力的计算每个数字中含有多少个1,我们可以使用动态规划的方法来计算i中有几个1。假设我们已经知道前i-1个数字分别有多少个1,而且i中含有k个数字,那么其实很容易的想到,i中1的个数等于前k-1位构成的数字的1的个数,加上第k位1的个数,即1或是0。还有一种等价的思路是第0位的1的个数(0或是1)加上1~k位构成的数字的1的个数。

    public int[] countBits(int num) {
          int[] ans = new int[num + 1];
          for (int i = 1; i <= num; ++i)
            ans[i] = ans[i & (i - 1)] + 1;
          return ans;
      }
    public int[] countBits(int num) {
        int[] res = new int[num+1];
        int cur = 1;
        while(cur <= num){
            res[cur] = 1;
            cur <<= 1;
        }
        
        cur = 1;
        for(int i = 1 ; i<=num ; i++){
            if(res[i] > 0){
                cur = i;
            }else{
                res[i] = res[i-cur] + 1;
            }
        }
        return res;
    }

clipboard.png
想要了解更多开发技术,面试教程以及互联网公司内推,欢迎关注我的微信公众号!将会不定期的发放福利哦~


raledong
2.7k 声望2k 粉丝

心怀远方,负重前行