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

 本文转自博客园Grandyang的博客,原文链接:全部汉明距离[LeetCode] Total Hamming Distance ,如需转载请自行联系原博主。

相关文章
|
6月前
【Leetcode -461.汉明距离 -482.密钥格式化】
【Leetcode -461.汉明距离 -482.密钥格式化】
26 0
LeetCode 461. 汉明距离
LeetCode 461. 汉明距离
67 0
LeetCode 461. 汉明距离
|
数据库 C语言
LeetCode 72. Edit Distance
给定两个单词word1和word2,找到将word1转换为word2所需的最小操作数。 您对单词允许以下3个操作: 插入一个字符 删除一个字符 替换一个字符
42 0
LeetCode 72. Edit Distance
|
算法 Java
《LeetCode刷题》—461.汉明距离
《LeetCode刷题》—461.汉明距离
82 0
《LeetCode刷题》—461.汉明距离
Leetcode-Easy 72. Edit Distance
Leetcode-Easy 72. Edit Distance
66 0
Leetcode-Easy 72. Edit Distance
|
算法
​LeetCode刷题实战477:汉明距离总和
算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试。所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从LeetCode上面选 !
103 0
|
算法
​LeetCode刷题实战461:汉明距离
算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试。所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从LeetCode上面选 !
77 0
LeetCode 训练场:461. 汉明距离
LeetCode 训练场:461. 汉明距离
89 0
|
算法 Python
<LeetCode天梯>Day047 汉明距离(位运算+内置函数) | 初级算法 | Python
<LeetCode天梯>Day047 汉明距离(位运算+内置函数) | 初级算法 | Python
<LeetCode天梯>Day047 汉明距离(位运算+内置函数) | 初级算法 | Python
LeetCode之Hamming Distance
LeetCode之Hamming Distance
98 0

热门文章

最新文章