leetcode 477 Total Hamming Distance

本文介绍了一种计算一组整数间所有可能配对的海明距离总和的方法,并提供了一个高效的C++实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

The Hamming distance between two integers is the number of positions at which the corresponding bits are different.
Now your job is to find the total Hamming distance between all pairs of the given numbers.
Example:
Input: 4, 14, 2

Output: 6

Explanation: In binary representation, the 4 is 0100, 14 is 1110, and 2 is 0010 (just
showing the four bits relevant in this case). So the answer will be:
HammingDistance(4, 14) + HammingDistance(4, 2) + HammingDistance(14, 2) = 2 + 2 + 2 = 6.

Note:
1. Elements of the given array are in the range of 0 to 10^9
2. Length of the array will not exceed 10^4.

本题难度在leetcode上标记为medium,其实并不难,关键是不要被total迷惑住,把握住hamming distance的定义就好。
关于 hamming distance:两个数各二进制位置上的不同位个数的总和。
只求两个数的海明距离简单异或即可得到答案,本题只要把异或过程拆开即可求解,类似之前做过的一道题目,那道题是求一个数组里的两个不同数分别是多少,关键的一步是利用不同数的二进制表达的最低位开始的某一位不同(0和1),凭借这一位将数组分为两堆,分别异或求解。
对于本题:

要求任意两个数的海明距离,根据上面的分析,海明距离是不同位的个数求和,对于数组中数的每一位,我们都可以把它分成两组,一组该位是0 另一组为1,对于每一位的分别求解,就可以得到对于该位上所有数的海明距离之和,最后将各位求和结果再求和,就得到了最终解。

实现代码如下(C++11):
class Solution {
public:
int totalHammingDistance(vector& nums) {

    int total = 0;
    int size = nums.size();
    for(int i = 0;i<32;i++) {
        int count = 0;
        for(auto&val:nums) {
            if((val>>i)&1) count++;
        }
        total+= count*(size-count);
    }
    return total;
}

};
`

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值