美文网首页
WEEK#6Dynamic Programming_Counti

WEEK#6Dynamic Programming_Counti

作者: DarkKnightRedoc | 来源:发表于2017-09-25 11:55 被阅读0次

    Description of the Problem

    Given a non-negative integer number num. For every number 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 runtime 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.


    Solution1 (Mathematical pattern)

    May R[i] = number of bits in i.
    i.e. R[5] = 2 because binary(5) = (101)
    We initial R[0] = 0, R[1] = 1, noticing such pattern :
    R[2] = R[0] + 1;
    R[3] = R[1] + 1;
    R[4] = R[0] + 1;
    R[5] = R[1] + 1;
    R[6] = R[2] + 1;
    R[7] = R[3] + 1;
    R[8] = R[0] + 1;

    image.png

    From which we can code like this :

    class Solution {
    public:
        vector<int> countBits(int num) {
            vector<int> results;
            int size = num + 1;
            results.resize(size);
            results[0] = 0;
            results[1] = 1;
            for (int i = 2 ; i < size; i++)
                results[i] = results[i - exp2(floor(log2(i)))] + 1;
            return results;
        }
    };
    
    Efficiency.png

    However, as can be seen, it's not the ideal solution


    Solution2

    using bit operation, efficiency improved a great deal.

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

    相关文章

      网友评论

          本文标题:WEEK#6Dynamic Programming_Counti

          本文链接:https://www.haomeiwen.com/subject/iibrextx.html