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)

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,473评论 0 10
  • 问题: Given a non negative integer number num. For every nu...
    Cloudox_阅读 163评论 0 0
  • pyspark.sql模块 模块上下文 Spark SQL和DataFrames的重要类: pyspark.sql...
    mpro阅读 9,537评论 0 13
  • 下班回来后,发现楼下的玻璃大门,蒙上一股白白的雾气。仔细朝玻璃上看,可以发现沾在上边细细地水珠。一打开,一股略略的...
    什一的什阅读 356评论 1 2
  • 自己的一个发小,36岁,国企,已然结婚,工作之余开了个小酒吧与水果店,小日子过的风声水起。前些时日微信与我...
    张姝315阅读 342评论 1 1