美文网首页
338 Counting Bits

338 Counting Bits

作者: 烟雨醉尘缘 | 来源:发表于2019-08-13 19:12 被阅读0次

    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]

    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.

    解释下题目:

    给定一个正数,然后返回它之前每一个数字中(二进制)的1的个数

    1. 动态规划

    实际耗时:1ms

    public int[] countBits(int num) {
        int[] res = new int[num + 1];
        for (int i = 1; i <= num; i++) {
            res[i] = res[i >> 1] + (i & 1);
        }
        return res;
    }
    

      那这种题目肯定是动态规划,重要的是理解的是一个数n的两倍其实就是后面加个0,所以就有了这个算法

    时间复杂度O(n)
    空间复杂度O(n)

    相关文章

      网友评论

          本文标题:338 Counting Bits

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