477. Total Hamming Distance

来源:互联网 发布:淘宝店铺标志制作 编辑:程序博客网 时间:2024/05/21 10:16

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, 2Output: 6Explanation: In binary representation, the 4 is 0100, 14 is 1110, and 2 is 0010 (justshowing 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:

按照提示的方法是会超时的,所以我们根据观察可以得到如下结论(copy from http://www.cnblogs.com/grandyang/p/6208062.html)

这道题是之前那道Hamming Distance的拓展,由于有之前那道题的经验,我们知道需要用异或来求每个位上的情况,那么我们需要来找出某种规律来,比如我们看下面这个例子,4,14,2和1:

4:     0 1 0 0

14:   1 1 1 0

2:     0 0 1 0

1:     0 0 0 1

我们先看最后一列,有三个0和一个1,那么它们之间相互的汉明距离就是3,即1和其他三个0分别的距离累加,然后在看第三列,累加汉明距离为4,因为每个1都会跟两个0产生两个汉明距离,同理第二列也是4,第一列是3。我们仔细观察累计汉明距离和0跟1的个数,我们可以发现其实就是0的个数乘以1的个数,发现了这个重要的规律,那么整道题就迎刃而解了,只要统计出每一位的1的个数即可,参见代码如下:

public class Solution {    public int totalHammingDistance(int[] nums) {        if(nums == null || nums.length == 0){            return 0;        }        int res = 0;        for(int i = 0; i<32; i++){            int count = 0;            for(int j=0; j<nums.length; j++){                if((nums[j]&1) == 1){                    count++;                }                nums[j] >>= 1;            }            res += count * (nums.length - count);        }        return res;    }}


原创粉丝点击