Skip to content

Latest commit

 

History

History
102 lines (84 loc) · 2.54 KB

477.md

File metadata and controls

102 lines (84 loc) · 2.54 KB
  1. 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, 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 to 10^9
Length of the array will not exceed 10^4.

my thoughts:

1. compare bit by bit from the back, each time separate the nums into 0s and 1s. the total distance at that bit is the len of 0s multiply the len of 1s. do it 32 times and sum up.

my solution:

**********716ms
class Solution(object):
    def totalHammingDistance(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        if len(nums)<2:
            return 0
        
        res = 0
        for i in range(32):
            l1 = 0
            l2 = 0
            temp = []
            for n in nums:
                if n&1:
                    l1 += 1
                else:
                    l2 += 1
                temp.append( n >> 1 )
            nums = temp
            res += l1 * l2

        return res           

my comments:



from other ppl's solution:

1. do the comparison from the front and back at the same time, 212ms:
class Solution(object):
    def totalHammingDistance(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        n = len(nums)
        
        ans = 0
        for i in xrange(16):
            cnt = 0
            for num in nums:
                cnt += (num >> i) & 0x10001
            
            cnt0, cnt1 = cnt & 0xFFFF, cnt >> 16
            ans += cnt0 * (n - cnt0) + cnt1 * (n - cnt1)
            
        return ans
		
2. count only 1s, the 0s is the total - 1s, 225ms:
class Solution(object):
    def totalHammingDistance(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        result = 0
        mask = 1
        for i in xrange(32):
            count = 0
            for a in nums:
                if a&mask:
                    count += 1
            result += (len(nums) - count) * count
            mask<<=1
        return result
		
3. one liner:
def totalHammingDistance(self, nums):
    return sum(b.count('0') * b.count('1') for b in zip(*map('{:032b}'.format, nums)))