總的海明距離 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;     } }

相關文章
相關標籤/搜索