477. Total Hamming Distance

Description

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:

  1. Elements of the given array are in the range of 0to 10^9
  2. Length of the array will not exceed 10^4.

Solution

Bit-manipulation, time O(n), space O(1)

用O(n^2)的countOneBit解法会TLE。换一种思路,按位考虑,按照第i位为0还是1将数组分成两个subset,然后就知道第i位的hamming distance了。这样只需要O(32 * n)的时间复杂度。

class Solution {
    public int totalHammingDistance(int[] nums) {
        int total = 0;
        int len = nums.length;
        
        for (int i = 0; i < 32; ++i) {
            int count = 0;
            for (int n : nums) {
                count += getDigit(n, i);
            }
            total += count * (len - count);
        }
        
        return total;
    }
    
    public int getDigit(int n, int digit) {
        return (n >> digit) & 1;
    }
}

你可能感兴趣的:(477. Total Hamming Distance)