Leetcode 477 汉明距离总和 位运算技巧

文章目录


问题导入
题目链接
在这里插入图片描述
B r i a n Brian Brian K e r n i g h a n Kernighan Kernighan 算法
f ( x ) f(x) f(x) 表示 x x x x − 1 x-1 x1 进行与运算所得的结果(即 f ( x ) f(x) f(x)= x x x & ( x − 1 ) (x−1) (x1)),那么 f ( x ) f(x) f(x) 恰为 x x x 删去其二进制表示中最右侧的 1 1 1 的结果。

时间复杂度: O ( log ⁡ C ) O(\log C) O(logC),其中 C C C 是元素的数据范围
空间复杂度: O ( 1 ) O(1) O(1)

class Solution {
public:
    int hammingDistance(int x, int y) {
        int s = x^y, res = 0;
        while(s)
        {
            s &= s - 1;
            res++;
        }
        return res;
    }
};

两个数之间不同位置 1 的数量升级为多个数两个数之间不同位置 1 的数量怎么求呢?
题目链接
在这里插入图片描述
暴力代码

class Solution {
public:
    int totalHammingDistance(vector<int>& nums) {
        int res = 0;
        for(int i = 0; i < nums.size(); i++)
        {
            for(int j = i + 1; j < nums.size(); j++)
            {
                int x = nums[i]^nums[j];
                while(x)
                {
                    x &= x - 1;
                    res++;
                }
            }
        }
        return res;
    }
};

这里利用位运算技巧,我们求 n n n 个数,每个二进制1位上 0 与 1 的个数,对于每个二进制位 1 与 0 的个数有个结论, n n n 个进制位,有 x x x 个 1,那么我们就有 n − x n-x nx 个 0,那么不同二进制位上 1 的个数有 y = x ∗ ( n − x ) y = x*(n-x) y=x(nx) 1 e 9 1e9 1e9 顶多枚举到 30 位二进制位。

class Solution {
public:
    int totalHammingDistance(vector<int>& nums) {
        int res = 0, n = nums.size();
        for(int i = 0; i <= 30; i++)
        {
            int c = 0;
            for(int j = 0; j < n; j++)
                c += (nums[j] >> i)&1;
            res += c*(n-c);
        }
        return res;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

幸愉信奥

谢谢亲的支持,我会继续努力啦~

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

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

打赏作者

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

抵扣说明:

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

余额充值