338 Counting Bits

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)