zoukankan      html  css  js  c++  java
  • 0338. Counting Bits (M)

    Counting Bits (M)

    题目

    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 1:

    Input: 2
    Output: [0,1,1]
    

    Example 2:

    Input: 5
    Output: [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.

    题意

    计算整数0-num的每一个数的二进制中的1的个数。要求时间复杂度为(O(N)),而非(O(kN))

    思路

    个人的做法是针对每一个整数num,它二进制中1的个数,就等于把它最高位的1去掉后得到的整数的二进制中1的个数加1,如8的二进制为1000,而去掉最高位1得到的整数为0,所以8的二进制中1的个数为0+1=1。

    更巧妙的方法是对于每个整数i,i&(i-1)的结果就相当于把i最右边的1变为0,这样很容易得到count[i] = count[i&(i-1)] + 1。


    代码实现

    Java

    去掉最高位

    class Solution {
        public int[] countBits(int num) {
            int[] count = new int[num + 1];
            count[0] = 0;
            int size = 1;
            int cnt = 0;
            for (int i = 1; i <= num; i++) {
                if (cnt == size) {
                    cnt = 0;
                    size *= 2;
                }
                count[i] = count[i - size] + 1;
                cnt++;
            }
            return count;
        }
    }
    

    去掉最右1

    class Solution {
        public int[] countBits(int num) {
            int[] count = new int[num + 1];
            count[0] = 0;
            for (int i = 1; i <= num; i++) {
                count[i] = count[i & (i - 1)] + 1;
            }
            return count;
        }
    }
    
  • 相关阅读:
    Python列表(即数组)
    Python中的关键字和内置函数
    python的变量和数据类型
    将数据写入本地txt
    Notepad++配置Python开发环境
    java中方法复写的作用进一步理解
    this表示当前对象的例子
    数组冒泡算法
    java实现星号三角形
    求1到1000之间同时能被3、5、7整除的数
  • 原文地址:https://www.cnblogs.com/mapoos/p/13217167.html
Copyright © 2011-2022 走看看