zoukankan      html  css  js  c++  java
  • Leetcode 338. Counting Bits.md

    题目

    链接:https://leetcode.com/problems/counting-bits

    **Level: ** Medium

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

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

    Note:

    • 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.

    代码一

    class Solution {
    public:
        vector<int> countBits(int num) {
            vector<int> d(num+1, 0);
            d[0]=0;
            for(int i=1;i<=num;i++)
            {
                d[i] = d[i&i-1]+1;  
            }
            return d;
        }
    };
    

    思考

    • 算法时间复杂度为O((n)),空间复杂度为O((n) )。
    • 这里观察到相邻两个整数转化为二进制的特点。当末位为0时,加1之后,二进制中1的个数就为前一个数的结果加1。当末位为1时,再加1,那么1会往前传递,1停在二进制为0的地方。比如1011,转化为1100,而曾经为1的地方变为0。此时i&i-1的意义在于取到相同的高位。而高位右边的各位必定只有一个传递过来的1。
    • vector数组可以初始化长度和值。这样做的好处是能节省一半的内存,因为使用push_back()时,vector会扩展此时所占空间一半的长度。所以如果已知所用空间的大小,直接固定长度进行初始化vector。

    代码二

    class Solution {
    public:
        vector<int> countBits(int num) {
            vector<int> d;
            d.push_back(0);
            for(int i=1;i<=num;i++)
            {
                int t = int(log2(i));
                int temp = pow(2,t)==i ? 1:d[i-pow(2,t)]+1;
                d.push_back(temp);
            }
            return d;
        }
    };
    
    

    思考

    • 算法时间复杂度为O((n)),空间复杂度为O((n) )。
    • 代码二是观察到高位去1后所得整数,转化为二进制中1的个数再加一,可得当前数二进制中1的个数。
    • 这里的复杂度分析应该不精确,因为不清楚log和pow的复杂度,但是想来应该和num的长度有关,note中提到的sizeof(integer)。运行出来也是代码二速度明显弱于代码一。
  • 相关阅读:
    MQ
    redis
    MongoDB
    进程相关命令
    catalina.sh
    tomcat-jvm
    中间件简介
    websphere
    mysql
    shell变量与字符串操作
  • 原文地址:https://www.cnblogs.com/zuotongbin/p/10553907.html
Copyright © 2011-2022 走看看