总的海明距离 Total Hamming Distance

问题:this

The Hamming distance between two integers is the number of positions at which the corresponding bits are different.spa

Now your job is to find the total Hamming distance between all pairs of the given numbers.code

Example:ip

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:get

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

解决:it

①  io

4:     0 1 0 0class

14:   1 1 1 0di

2:     0 0 1 0时间

总的汉明距离 = (2 * 1) + (2 * 1) + (2 * 1) + (3 * 0) = 6,因此总的汉明距离为每一个位上的1和0的数量,而后将它们相乘,而后将全部位的乘积相加。时间:O(N) ;空间: O(1)。

public class Solution { //19ms     public int totalHammingDistance(int[] nums) {         int sum = 0;         for (int i = 0; i < 32; i ++) {             int count = 0;             for (int num : nums) {                 count += (num >> i) & 1;             }             sum += count * (nums.length - count);         }         return sum;     } }

相关文章
相关标签/搜索