leetcode477. 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:
1. Elements of the given array are in the range of 0 to 10^9
2. Length of the array will not exceed 10^4.

計算N個數字之間的漢明碼距離之和。
漢明碼是指兩個數字的二進制表示形式中,在對應位置上值不同的數量總和。如2和4,4的二進制表達式爲100, 2的二進制表達式010,則二者在第二位和第三位的值不同,因此漢明碼值爲2。

思路和代碼

如果直觀的採用兩兩比較來得出任意兩個數字之間的漢明碼值,再將漢明碼值的和進行累加,得出最終的漢明碼值總和,則需要O(n^2)的時間複雜度。除此以外,還要乘上數字二進制的平均長度。

那麼有沒有方法能夠儘可能的減少重複比較的場景。既然水平的以兩個數字直接開始比較會超時,不如垂直的進行比較,即每次都比較同一位置上的所有二進制數值,假設一共有n個數字,其中有m個數字在第i上值爲1,則剩下的n-m個數字在第i上的值爲0。由此可知,在第i爲上存在的(m-n)*n個數值不同的情況。對32位整數重複執行這個過程並累加即可得出最終的漢明碼和。

代碼如下:

    public int totalHammingDistance(int[] nums) {
         int count = 0;
         int length = nums.length;
         for(int i = 0 ; i<32 ; i++) {
               int countOfOne = 0;
               for(int j = 0 ; j < length ; j++) {
                   countOfOne += (nums[j] >> i) & 1;
               }
               count += countOfOne * (length - countOfOne);
         } 
         return count;
     }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章