【12月19日】LeetCode刷题日志(二):Hamming Distance

package com.njust.med.totalhammingdistance;

/**
 * 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.
 * leecode上关于汉明距离的题目很多。汉明距离:汉明距离是使用在数据传输差错控制编码里面的,汉明距离是一个概念,它表示两个
 *(相同长度)字对应位不同的数量,我们以d(x,y)表示两个字x,y之间的汉明距离。对两个字符串进行异或运算,并统计结果为1的个数,那么这个数就是汉明距离。
 * 思路1:利用在easy中的hammingdistace进行计算-->此思路在测试集运行到哦最后一个的时候超时
 *
 * 思路2:leetcode上的高票答案 -- 厉害
 * 数组里面的元素都看成是一个32位二进制;逐位进行统计。
 * 例如,先统计第一位上所有元素的值,令nums数组中所有元素的第一位中,有bitCount个1,对应的有n-bitCount个0,
 * 仅根据以上信息就可以推断这些差异会对hamming距离贡献bitCount*(n - bitCount)
 *
 *
 * public int totalHammingDistance(int[] nums) {
 * int total = 0, n = nums.length;
 * for (int j=0;j<32;j++) {
 * int bitCount = 0;
 * for (int i=0;i<n;i++)
 * bitCount += (nums[i] >> j) & 1;
 * total += bitCount*(n - bitCount);
 * }
 * return total;
 * }
 *
 */
public class Solution {

    public int hammingDistance(int x, int y) {
        return Integer.bitCount(x ^ y);
    }

    public int totalHammingDistance(int[] nums) {
        int result = 0;
        int  j = 1;
        int len = nums.length;
        while (j<len){
           for (int i=0;i<j;i++){
               result += hammingDistance(nums[i],nums[j]);
           }
            j++;
        }
        return result;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值