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.

解釋下題目:

給定一個(gè)正數(shù),然后返回它之前每一個(gè)數(shù)字中(二進(jìn)制)的1的個(gè)數(shù)

1. 動(dòng)態(tài)規(guī)劃

實(shí)際耗時(shí):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;
}

??那這種題目肯定是動(dòng)態(tài)規(guī)劃,重要的是理解的是一個(gè)數(shù)n的兩倍其實(shí)就是后面加個(gè)0,所以就有了這個(gè)算法

時(shí)間復(fù)雜度O(n)
空間復(fù)雜度O(n)

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi閱讀 7,424評(píng)論 0 10
  • 問(wèn)題: Given a non negative integer number num. For every nu...
    Cloudox_閱讀 163評(píng)論 0 0
  • pyspark.sql模塊 模塊上下文 Spark SQL和DataFrames的重要類: pyspark.sql...
    mpro閱讀 9,504評(píng)論 0 13
  • 下班回來(lái)后,發(fā)現(xiàn)樓下的玻璃大門,蒙上一股白白的霧氣。仔細(xì)朝玻璃上看,可以發(fā)現(xiàn)沾在上邊細(xì)細(xì)地水珠。一打開,一股略略的...
    什一的什閱讀 338評(píng)論 1 2
  • 自己的一個(gè)發(fā)小,36歲,國(guó)企,已然結(jié)婚,工作之余開了個(gè)小酒吧與水果店,小日子過(guò)的風(fēng)聲水起。前些時(shí)日微信與我...
    張姝315閱讀 329評(píng)論 1 1