[LeetCode] 477. 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 to 10^9
  2. Length of the array will not exceed 10^4.

 

這道題是之前那道 Hamming Distance 的拓展,由於有之前那道題的經驗,我們知道需要用異或來求每個位上的情況,那么需要來找出某種規律來,比如看下面這個例子,4,14,2 和1:

4:     0 1 0 0

14:   1 1 1 0

2:     0 0 1 0

1:     0 0 0 1

先看最后一列,有三個0和一個1,那么它們之間相互的漢明距離就是3,即1和其他三個0分別的距離累加,然后在看第三列,累加漢明距離為4,因為每個1都會跟兩個0產生兩個漢明距離,同理第二列也是4,第一列是3。仔細觀察累計漢明距離和0跟1的個數,可以發現其實就是0的個數乘以1的個數,發現了這個重要的規律,那么整道題就迎刃而解了,只要統計出每一位的1的個數即可,參見代碼如下:

 

class Solution {
public:
    int totalHammingDistance(vector<int>& nums) {
        int res = 0, n = nums.size();
        for (int i = 0; i < 32; ++i) {
            int cnt = 0;
            for (int num : nums) {
                if (num & (1 << i)) ++cnt;
            }
            res += cnt * (n - cnt);
        }
        return res;
    }
};

 

Github 同步地址:

https://github.com/grandyang/leetcode/issues/477

 

類似題目:

Hamming Distance

 

參考資料:

https://leetcode.com/problems/total-hamming-distance/

https://leetcode.com/problems/total-hamming-distance/discuss/96226/Java-O(n)-time-O(1)-Space

https://leetcode.com/problems/total-hamming-distance/discuss/96243/Share-my-O(n)-C%2B%2B-bitwise-solution-with-thinking-process-and-explanation

 

LeetCode All in One 題目講解匯總(持續更新中...)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM