Total Hamming Distance

来源:互联网 发布:mac os 10.7软件推荐 编辑:程序博客网 时间:2024/06/16 20:29

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, 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.
解析:首先想到的是每对数进行异或,然后求取异或后中1的个数,这个时间复杂度为

O(n^2),超时,后来知道因为每位数都要进行比较,所以直接求取每位数中为1的数有多少,然后跟为0的个数相乘即是这个位的Hamming Distance.

代码:

class Solution {public:    int totalHammingDistance(vector<int>& nums) {    /*    int N=nums.size();        int ans=0;        for (int i=0; i<N; i++)        {            for (int j=i+1; j<N; j++)            {                int temp=nums[i]^nums[j];                ans+=Numberof1(temp);            }        }        return ans;    }        int Numberof1(int n)    {        int count=0;        while(n)        {            ++count;            n=(n-1)&n;        }        return count;    }*/        int N=nums.size();    int ans=0;    for (int i=0; i<32; i++)    {        int numcount=0;        for (int j=0; j<N; j++)        {            numcount+=((nums[j]>>i)&1);        }        ans+=(numcount*(N-numcount));    }    return ans;    }};






0 0
原创粉丝点击