• 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;
        }
    }
    
  • 相关阅读:
    “北漂”的那些年 5
    “北漂”的那些年 4
    全国省市区代码-2020版
    记一次CDH修改IP
    Python爬取抖音视频
    代码生成,减少70%的重复劳动
    Log4J配置详解
    linux常用命令
    tomcat修改默认访问首页
    java根据身份证号和获取用户年龄和性别的工具类
  • 原文地址:https://www.cnblogs.com/mapoos/p/13217167.html
Copyright © 2020-2023  润新知