java数据结构与算法刷题-----LeetCode338. 比特位计数

java数据结构与算法刷题目录(剑指Offer、LeetCode、ACM)-----主目录-----持续更新(进不去说明我没写完):https://blog.youkuaiyun.com/grd_java/article/details/123063846

在这里插入图片描述

位运算统计1的个数

🏆LeetCode461. 汉明距离https://blog.youkuaiyun.com/grd_java/article/details/137608654

461题考察的就是统计二进制串中1的个数。其中BK算法是经典算法,这里也使用BK来实现

解题思路:时间复杂度O( n ∗ l o g 2 n n*log_2n nlog2n),空间复杂度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++){//对每个数字进行BK算法统计1的个数
            int count = 0;//统计1的个数
            int num = i;//获取当前数字
            while(num!=0){//只要num的二进制串还有1就继续
                num &= (num-1);//去掉最右边的1
                count++;//每去一个,count+1
            }
            ans[i] = count;//保存当前数字中二进制1的个数
        }
        return ans;
    }
}

动态规划

解题思路:时间复杂度O( n n n),空间复杂度O( 1 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);//从1开始算1的个数
        return res;
    }
    //动态规划
    private void dfs(int i, int count, int n) {
        if (i > n) return;//如果i>n则无需继续统计,因为我们只要0-n的二进制1的个数
        res[i] = count;//将当前i的1的个数保存
        dfs(i << 1, count, n);//i左位移1位,相当于乘2.1的个数不变。例如1,左移一位10
        dfs((i << 1) + 1, count + 1, n);//i左位移1位后,+1,1的数量+1,例如1,左移一位10,+1后11.正好覆盖所有情况
    }
}
代码2. 最低有效位

在这里插入图片描述

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;
    }
}
代码3. 最低设置位

在这里插入图片描述

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;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ydenergy_殷志鹏

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值