Sunday, December 25, 2016

477. Total Hamming Distance

Q:

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 to 10^9
  2. Length of the array will not exceed 10^4.

A:

首先实验brute Force算法,我是想或许通过调整# of ones可以通过,但是还是TLE了

public class Solution {
    public int totalHammingDistance(int[] nums) {
        int n = nums.length, res = 0;
        for(int i =0;i<n;i++){
            for(int j = i+1;j<n;j++){
                res+= nOnes(nums[i]^nums[j]);
            }
        }
        return res;
    }
    private int nOnes(int a){
        int res = 0;
        while(a!=0){
            res++;
            a = a&(a-1);
        }
        return res;
    }
}


--------因此,每一位开始比较,----------其实就是每一位的1的个数乘以0的个数--------

public class Solution {
    public int totalHammingDistance(int[] nums) {
        int n = nums.length, res = 0;
        for(int k =0;k<32;k++){
            int mask = 1<<k;
            int numOf1s = 0;
            for(int i =0;i<n;i++)
                if( (nums[i] & mask) !=0)
                    numOf1s ++;
            res += numOf1s * (n-numOf1s);
        }
        return res;
    }
}



Errors:





No comments:

Post a Comment