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.
在這裏提供三種時間複雜度是線性的解法
第一種
public static int[] countBits(int num) {
int[] result = new int[num+1];
if (num == 0) {
result[0] = 0;
return result;
}
result[0] = 0;
for(int i=1;i<num+1;i++){
int tail=i%2;
int count=i/2;
result[i]=tail+result[count];
}
return result;
}
第二種
public int[] countBits(int num) {
int[] m=new int[16];
m[0] = 0;
m[1] = 1;
m[2] = 1;
m[3] = 2;
m[4] = 1;
m[5] = 2;
m[6] = 2;
m[7] = 3;
m[8] = 1;
m[9] = 2;
m[10] = 2;
m[11] = 3;
m[12] = 2;
m[13] = 3;
m[14] = 3;
m[15] = 4;
int[] ret=new int[num+1];
for(int i = 0; i <= num; i++) {
ret[i] = m[i&15] + m[(i>>4)&15] + m[(i>>8)&15] +m[(i>>12)&15] + m[(i>>16)&15] + m[(i>>20)&15] + m[(i>>24)&15] + m[(i>>28)&15];
}
return ret;
}
第三種解法
public int[] countBits(int num) {
int i,j,count;
int res[] = new int[num+1];
i = j = 0;
while(i <= num){
j = i;
count = 0;
while(j != 0){
j = j&(j-1);
count++;
}
res[i] = count;
i++;
}
return res;
}