【LeetCode-477】Total Hamming Distance

来源:互联网 发布:java反射的作用 编辑:程序博客网 时间:2024/05/21 18:44

题目:
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
原创粉丝点击