We have an array A (say [1,2,3])
. We need to find the XOR(^)SUM of all pairs of integers in the array. Though this can easily be done in O(n^2)
but how can i improve the complexity of the solution ? E.g for the above array , A, the answer would be (1^2)+(1^3)+(2^3) = 6
Thanks.
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.
Note:
- Elements of the given array are in the range of
0
to10^9
- Length of the array will not exceed
10^4
.
用另外的思路来解决。32bit的整数,我们每次只看其中的1位。
比如,只看 nums 数组中所有数字的rightmost bit. 如果有 i
个数字的rightmost bit是 0
,有j
个数字的rightmost bit是 1
,那么 i * j
将会是这一位上汉明距离增加的值。
如:0100
1110
0010
0110
1010
看最左一位,有3个数字中这一位是0,有2个数字中这一位是1。0 0 0 1 1,对于其中一个这一位是0的数,它要跟另外2个这一位是1的数配对,所以对于这一位,汉明距离要+2。其他这一位是0的数同理,汉明距离都要+2。因此结果是2+2+2,也就是2*3。
public int totalHammingDistance(int[] nums) {
int n=nums.length;
int total=0;
for(int i=0;i<32;i++){
int countOf_1=0;
for(int j=0;j<n;j++){
countOf_1 += ( (nums[j]>>i) & 1 );
}
total+=countOf_1*(n-countOf_1);
}
return total;
}
For each bit position 1-32 in a 32-bit integer, we count the number of integers in the array which have that bit set. Then, if there are n integers in the array and k of them have a particular bit set and (n-k) do not, then that bit contributes k*(n-k) hamming distance to the total.
参考资料:https://stackoverflow.com/questions/21388448/sum-of-xor-values-of-all-pairs
因为stackoverflow经常打不开或者打开非常慢,因此我直接复制在下面。
sum of xor values of all pairs

3
1
| |
11
|
You can separate the calculation to do one bit at a time. For example, look at the rightmost bit of all the numbers in the array. Suppose that In general, when looking at the This can be done in O(kn) time, where | ||||||||||||||||
|
1^2+1^3+2^3 = 3 + 2 + 1 = 6
. – Matt Jan 27 '14 at 18:30[1,2,2]
? Is it(1^2)+(1^2)=6
, or1^2=3
? If it's the first, then it is unnecessary to specify "distinct pairs" in the question since2^2=0
anyway and wouldn't contribute to the sum. – Matt Jan 27 '14 at 18:44