Press "Enter" to skip to content

Posts tagged as “hamming”

花花酱 LeetCode 477. Total Hamming Distance

Problem:

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:

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.

题目大意:给你一堆数,让你求所有数对的HammingDistance的总和。

Idea:

  1. Brute force, compute HammingDistance for all pairs. O(n^2) TLE
  2. Count how many ones on i-th bit, assuming k. Distance += k * (n – k). O(n)

Solution:

C++ / O(n)