Leet Code OJ 338. Counting Bits [Difficulty: Medium]


タイトル: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. Hint: You should make use of what you have produced already.
非負の整数numが与えられ、0<=i<=numの整数iごとにiのバイナリ表現の1の個数が計算され、これらの個数が配列として返される.たとえばnum=5と入力すると、[0,1,2,1,2]に戻るはずです.
解析:従来の考え方では「Javaコード2」のシナリオが容易に得られるが,このシナリオの時間的複雑度はO(nlogn)である.配列の最初の64要素を分析することによって(num=63)、配列は一定の法則を呈し、次の図に示すように繰り返していることが分かった.
0 
1 
1 2 
1 2 2 3 
1 2 2 3 2 3 3 4 
1 2 2 3 2 3 3 4 2 3 3 4 3 4 4 5 
1 2 2 3 2 3 3 4 2 3 3 4 3 4 4 5 2 3 3 4 3 4 4 5 3 4 4 5 4 5 5 6 

これにより、0112は基礎要素であり、繰り返し繰り返し繰り返し、第1の要素がresult[0]であることが知られている場合、第2の第3の要素はresult[0]+1、第4の要素はresult[0]+2であり、これによって前の4つの要素result[0]~result[3]が得られると推論できる.この4つの要素に基づいて、result[4]=result[0]+1、result[5]=result[1]+1...、result[8]=result[0]+1、result[9]=result[1]+1...、result[12]=result[0]+2、result[13]=result[1]+2...;このようにしてすべての配列を得ることができる.
Java版コード1:
public class Solution {
    public int[] countBits(int num) {
        int[] result = new int[num + 1];
        int range = 1;
        result[0] = 0;
        boolean stop = false;
        while (!stop) {
            stop = fillNum(result, range);
            range *= 4;
        }
        return result;
    }

    public boolean fillNum(int[] nums, int range) {
        for (int i = 0; i < range; i++) {
            if (range + i < nums.length) {
                nums[range + i] = nums[i] + 1;
            } else {
                return true;
            }
            if (2 * range + i < nums.length) {
                nums[2 * range + i] = nums[i] + 1;
            }
            if (3 * range + i < nums.length) {
                nums[3 * range + i] = nums[i] + 2;
            }
        }
        return false;
    }
}

Java版コード2:
public class Solution {
    public int[] countBits(int num) {
        int[] result=new int[num+1];
        result[0]=0;
        for(int i=1;i<=num;i++){
            result[i]=getCount(i);
        }
        return result;
    }
    public int getCount(int num){
        int count=0;
        while(num!=0){
            if((num&1)==1){
                count++;
            }
            num/=2;
        }
        return count;
    }
}