338. 比特位计数

题目描述:

  给定一个非负整数 num。对于 0 ≤ i ≤ num 范围中的每个数字 i ,计算其二进制数中的 1 的数目并将它们作为数组返回。

  示例 1:

    输入: 2
    输出: [0,1,1]
  示例 2:

    输入: 5
    输出: [0,1,1,2,1,2]
  进阶:

    给出时间复杂度为O(n*sizeof(integer))的解答非常容易。但你可以在线性时间O(n)内用一趟扫描做到吗?
  要求算法的空间复杂度为O(n)。
  你能进一步完善解法吗?要求在C++或任何其他语言中不使用任何内置函数(如 C++ 中的 __builtin_popcount)来执行此操作。

解答:

public class L338 {
    //方法1-普通方法
    public int[] countBits(int num) {
        int[] ans = new int[num + 1];
        for (int i = 0; i <= num; ++i)
            ans[i] = popcount(i);
        return ans;
    }
    //动态规划--利用到方法1: ans[num] = ans[num & (num-1)] + 1;
    public int[] countBits2(int num){
        int[] res = new int[num+1];
        for(int index=1; index<=num;index++){
            res[index] = res[index & (index-1)] + 1;
        }
        return res;
    }
    /**动态规划--利用ans[num] = ans[num/2] + num%2
    * 例如:观察x 和 x' 的关系
     * x = (1001011101)_2 = (605)
     * x' = (100101110)_2 = (302)
     * 他们之间1的个数差一个
     *如果x为偶数
     * x = (1001011100)_2 = (604)
     * x' = (100101110)_2 = (302)
     * 他们之间1的个数相同*/
    public int[] countBits3(int num){
        int[] res = new int[num+1];
        for(int index=1; index<=num;index++){
            res[index] = res[index >> 1] + index & 1;
        }
        return res;
    }
    /*求一个数二进制的1的个数
    * 算法思路:每次for循环,都将num的二进制中最右边的 1 清除。
      *为什么n &= (n – 1)能清除最右边的1呢?因为从二进制的角度讲,n相当于在n - 1的最低位加上1。
      * 举个例子,8(1000)= 7(0111)+ 1(0001),所以8 & 7 = (1000)&(0111)= 0(0000),
      * 清除了8最右边的1(其实就是最高位的1,因为8的二进制中只有一个1)。再比如7(0111)= 6(0110)+ 1(0001),
      * 所以7 & 6 = (0111)&(0110)= 6(0110),清除了7的二进制表示中最右边的1(也就是最低位的1)。*/
    private int popcount(int x) {
        int count;
        for (count = 0; x != 0; ++count)
            x &= x - 1; //zeroing out the least significant nonzero bit
        return count;
    }
}

 

posted @ 2019-12-07 13:32  努力学习~~~  阅读(170)  评论(0编辑  收藏  举报