leetcode解题: Counting Bits (338)

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.
Divide the numbers in ranges like [2-3], [4-7], [8-15] and so on. And try to generate new range from previous.
Or does the odd/even status of the number help you in calculating the number of 1s?

解法1:找规律, O(N)

本题比较简单的解法也是从找规律而来
0 -> 0
1 -> 1
2 -> 10 -> 1
3 -> 11 -> 2
4 -> 100 -> 1
5 -> 101 -> 2
对于偶数i,他的1的个数是i/2的1的个数
杜宇奇数i,他的1的个数是i/的1的个数+1

因为对于一个数除以2的操作就是一个右移操作,而偶数的最低位为0,奇数的最低位为1, 那么右移的时候偶数的1的个数不会变,奇数的1的个数会减少1. 由此写出程序。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public:
vector<int> countBits(int num) {
if (num == 0) {
return vector<int>{0};
} else if (num == 1) {
return vector<int>{0,1};
}
vector<int> res{0,1};
for (int i = 2; i <= num; ++i) {
if (i % 2 == 0) {
res.push_back(res[i/2]);
} else {
res.push_back(res[i/2] + 1);
}
}
return res;
}
};

解法2: HashMap

观察现象可以发现,每一个数字如果是2的幂次,那么1的个数为1.如果不是,则 = 1 + dp[数字 - 最接近这个数的2的幂次数]
这里dp记录的是每一个数字的1的个数。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Solution {
public int[] countBits(int num) {
if (num == 0) return new int[]{0};
if (num == 1) return new int[]{0, 1};
int[] res = new int[num + 1];
res[0] = 0;
res[1] = 1;
Map<Integer, Integer> map = new HashMap<>();
map.put(0, 0);
map.put(1, 1);
int largest = 1;
for (int i = 2; i <= num; i++) {
if ( ( i & (i - 1)) == 0) {
res[i] = 1;
map.put(i, 1);
largest = i;
} else {
res[i] = 1 + map.get(i - largest);
map.put(i, res[i]);
}
}
return res;
}
}

解法3:

观察现象,如果是偶数,则结果和偶数/2一样,如果是奇数,那么是奇数/2 + 1.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
public int[] countBits(int num) {
if (num == 0) {
return new int[]{0};
}
if (num == 1) {
return new int[]{0, 1};
}
int[] res = new int[num + 1];
res[0] = 0;
res[1] = 1;
for (int i = 2; i <= num; i++) {
res[i] = i % 2 == 0 ? res[i >> 1] : res[i >> 1] + 1;
}
return res;
}
}