题目
给定一个非负整数 n ,请计算 0 到 n 之间的每个数字的二进制表示中 1 的个数,并输出一个数组。
示例 1:
输入: n = 2
输出: [0,1,1]
解释:
0 --> 0
1 --> 1
2 --> 10
示例 2:
输入: n = 5
输出: [0,1,1,2,1,2]
解释:
0 --> 0
1 --> 1
2 --> 10
3 --> 11
4–> 100
5 --> 101
说明 :
0 <= n <= 105
进阶:
给出时间复杂度为 O(n*sizeof(integer)) 的解答非常容易。但你可以在线性时间 O(n) 内用一趟扫描做到吗?
要求算法的空间复杂度为 O(n) 。 你能进一步完善解法吗?
要求在C++或任何其他语言中不使用任何内置函数(如 C++ 中的 __builtin_popcount )来执行此操作。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/w3tCBm
一、代码
这题的解法很多很多:
一、
最简单的思路:遍历0-n的每一个数temp,循环右移temp再去&1,从而计算temp的1的数量,再添加到res中。
优化:如果当前位奇数,那么1的数量必定为上一个偶数1的数量+1;
public int[] countBits(int n) {
int[] res =new int[n+1];int x =0;
for(int i=0;i<=n;i++){
int temp = i;
int cur=0;
//因为如果当前为奇数,那1的数量必定为上一个偶数的1的数量加一;
if((i&1)==1){
cur = res[x-1];
res[x++]=cur+1;
}else{
while(temp>0){
if((temp&1)==1) cur++;
temp>>=1;
}
res[x++]=cur;
}
}
return res;
}
二、
利用 Brian Kernighan 算法
原理为:对于任意整数 x,令 x= x & (x-1),该运算将 x 的二进制表示的最后一个 1 变成 0。因此,对 x 重复该操作,直到 x 变成 0,则操作次数即为 x 的1的个数。
例如:x=1010
1010 &1001 = 1000
1000 & 0111 = 0000
public int[] countBits(int n) {
int[] bits = new int[n + 1];
for (int i = 0; i <= n; i++) {
bits[i] = countOnes(i);
}
return bits;
}
public int countOnes(int x) {
int ones = 0;
while (x > 0) {
x &= (x - 1);
ones++;
}
return ones;
}
三、
在方法二的原理上,使用动态规划
x 比 x & (x-1) 多一个1
public int[] countBits(int n) {
int[] bits = new int[n + 1];
for (int i = 1; i <= n; i++) {
//原理和 i与i&(i-1)关系一样 i&(i-1)会消去i最右边的1
bits[i] = bits[i & (i - 1)] + 1;
}
return bits;
}
四、
动态规划
比如:
10110与1011,10110 >>1=1011
所以只要知道当前 (i>>1)的1 的个数,
再去判断 i 最右边的数是1还是0,就可以得到 i 的 1 的个数。
public int[] countBits(int n) {
int[] res = new int[n+1];
for(int i = 1; i <= n; i++){
// res[i] = res[i>>1] + i % 2;
res[i] = res[i>>1] + (i & 1);
}
return res;
}
侵删