【LeetCode-477】Total Hamming Distance

题目:
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.

解题思路:使用暴力解决的方式超时了,不得不寻找更简单的方法,不卖官司了,直接说思路吧。
由于每一个数都是int型,因此每一个整数由32位组成,符号位由于都是正数,因此可以忽略,那剩下31位;
接下来建立一个大小为31的数组,分别存储第i位上为0的数的个数。
那么异或后第i位上1的个数 = 第i位上0的个数 * 第i位上1的个数,一共31位,最后做一个累加就好了。

public class TotalHammingDistance477 {
    public int totalHammingDistance(int[] nums) {
        if(nums == null || nums.length == 0) return 0;
        int res = 0, len = nums.length;
        int[] map = new int[31];

        for(int i : nums) for(int j = 0; j < 31; j++) map[j] += (i & (1 << j)) == 0 ? 1 : 0;

        //map[i]为第i位为0的数量(该位1的数量 * 0的数量 = 异或后1的数量)
        for(int i = 0; i < 31; i++) res += map[i] * (len - map[i]);

        return res;
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值