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:
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 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ù)n,然我們統(tǒng)計(jì)從0到n每個(gè)數(shù)的二進(jìn)制寫(xiě)法的1的個(gè)數(shù),存入一個(gè)一維數(shù)組中返回。
規(guī)律是,從1開(kāi)始,遇到偶數(shù)時(shí),其1的個(gè)數(shù)和該偶數(shù)除以2得到的數(shù)字的1的個(gè)數(shù)相同,遇到奇數(shù)時(shí),res[i] = res[i-1] + 1 或者res[i/2]+1 (因?yàn)閕-1為偶數(shù))

public class Solution {
    public int[] countBits(int num) {
        int[] res = new int[num+1];
        if(num == 0) return res;
        res[0] = 0;
        res[1] = 1;
        for(int i=1; i<=num; i++){
            if(i%2 == 0) res[i] = res[i/2];
            else res[i] = res[i-1] + 1;
            // or res[i] = res[i/2] + 1;
        }
        
        return res;
    }
}

二刷
dynamic programming

class Solution {
    public int[] countBits(int num) {
        int[] res = new int[num+1];
        if(num == 0) return res;
        res[0] = 0;
        res[1] = 1;
        for(int i=2; i<=num; i++){
            if((i&1) == 1) res[i] = res[i-1] + 1;
            else res[i] = res[i/2];
        }
        return res;
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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