[leetcode]477. Total Hamming Distance

[leetcode]477. Total Hamming Distance


Analysis

等国庆等国庆!!!!!—— [每天刷题并不难]

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.
计算一个数组里的数字的Hamming Distance总和。

Implement

方法一(暴力,会超时)

class Solution {
public:
    int totalHammingDistance(vector<int>& nums) {
        int res = 0;
        int len = nums.size();
        for(int i=0; i<len-1; i++){
            for(int j=i+1; j<len; j++)
                res += HD(nums[i], nums[j]);
        }
        return res;
    }
    int HD(int num1, int num2){
        int res = 0;
        for(int i=0; i<32; i++){
            if((num1 & (1<<i)) ^ (num2 & (1<<i)))
                res++;
        }
        return res;
    }
};

方法二(先统计数组中的数在某一位上为1的个数,那么在这一位的海明距离就是为1的个数乘以为0的个数,然后依次统计出32位上的海明距离,最后相加得到结果)

class Solution {
public:
    int totalHammingDistance(vector<int>& nums) {
        int res = 0;
        int len = nums.size();
        for(int i=0; i<32; i++){
            int cnt = 0;
            for(auto num:nums){
                if(num & (1<<i))
                    cnt++;
            }
            res += cnt*(len-cnt);
        }
        return res;
    } 
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值