1. 程式人生 > >[LeetCode] Total Hamming Distance 全部漢明距離

[LeetCode] 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; } };

類似題目: