
位运算统计1的个数
461题考察的就是统计二进制串中1的个数。其中BK算法是经典算法,这里也使用BK来实现
解题思路:时间复杂度O(
n
∗
l
o
g
2
n
n*log_2n
n∗log2n),空间复杂度O(
1
1
1) |
---|
依次计算从0到n的每个数字的二进制中1的个数,遍历0-n需要n时间复杂度,而BK算法需要logn的时间复杂度

class Solution {
public int[] countBits(int n) {
int ans[] = new int[n+1];
for(int i = 0;i<n+1;i++){
int count = 0;
int num = i;
while(num!=0){
num &= (num-1);
count++;
}
ans[i] = count;
}
return ans;
}
}
动态规划
解题思路:时间复杂度O(
n
n
n),空间复杂度O(
1
1
1) |
---|
想要作图来表示,但是有些复杂,日后排版完成后再放上来

class Solution {
public int[] countBits(int n) {
int[] bits = new int[n + 1];
int highBit = 0;
for (int i = 1; i <= n; i++) {
if ((i & (i - 1)) == 0) {
highBit = i;
}
bits[i] = bits[i - highBit] + 1;
}
return bits;
}
}

class Solution {
int[] res;
public int[] countBits(int n) {
res = new int[n + 1];
dfs(1, 1, n);
return res;
}
private void dfs(int i, int count, int n) {
if (i > n) return;
res[i] = count;
dfs(i << 1, count, n);
dfs((i << 1) + 1, count + 1, n);
}
}

class Solution {
public int[] countBits(int n) {
int[] bits = new int[n + 1];
for (int i = 1; i <= n; i++) {
bits[i] = bits[i >> 1] + (i & 1);
}
return bits;
}
}

class Solution {
public int[] countBits(int n) {
int[] bits = new int[n + 1];
for (int i = 1; i <= n; i++) {
bits[i] = bits[i & (i - 1)] + 1;
}
return bits;
}
}