leetcode 477. Total Hamming Distance 任意两个数字的汉明距离之和

来源:互联网 发布:php开发实例大全 编辑:程序博客网 时间:2024/05/29 17:38

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

这道题是之前那道leetcode 461. 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的个数即可

代码如下:

#include <iostream>#include <vector>#include <map>#include <set>#include <queue>#include <stack>#include <string>#include <climits>#include <algorithm>#include <sstream>#include <functional>#include <bitset>#include <cmath>using namespace std;class Solution {public:    int totalHammingDistance(vector<int>& nums)    {        int res = 0;        for (int i = 0; i < 32; i++)        {            int count = 0;            for (int a : nums)            {                if (a & (1 << i))                    count++;            }            res += count * (nums.size() - count);        }        return res;    }    //下面通过位运算和循环来做的,不过超时了    int totalHammingDistanceByLoop(vector<int>& nums)    {        int sum = 0;        for (int i = 0; i < nums.size(); i++)        {            for (int j = i + 1; j < nums.size(); j++)            {                sum += getHanmmingDistance(nums[i], nums[j]);            }        }        return sum;    }    int getHanmmingDistance(int a, int b)    {        int n = a^b;        int count = 0;        while (n > 0)        {            count++;            n = n&(n - 1);        }        return count;    }};
原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 皮肤有一片红痒怎么办 脸过敏期间很干怎么办 怀孕了用了消糜栓怎么办 乳酸杆菌少或无怎么办 怀孕了白带有异味怎么办 怀孕清洁度iv度怎么办 怀孕了下面有异味怎么办 孕妇尿白细胞1是怎么办 药流期间喂奶了怎么办 20多岁卵巢早衰怎么办 3岁儿童肚子胀气怎么办 肚子又胀又痛怎么办 1岁宝宝肚子胀气怎么办 2岁宝宝肚子胀气怎么办 产后腰粗肚子大怎么办 发烧后腹泻拉水怎么办 又吐又拉还发烧怎么办 喝中药恶心想吐怎么办 生完孩子肛门疼怎么办 拉完大便肛门痛怎么办 肚子总是凉凉的怎么办 京东金条风控了怎么办 京东维修没发票怎么办 假牙吞到肚子里怎么办 眼睛一只大一只小怎么办 一个眼睛大一个眼睛小怎么办 电脑上的字模糊怎么办 无忧乐行注销了怎么办 连供墨盒有空气怎么办 30岁突然停经了怎么办 下面很痒怎么办白带多 私处有点痒怎么办洗液 人的下体皮肤痒怎么办 打球手指关节肿了怎么办 婴儿2个月鼻塞怎么办 3个月婴儿鼻塞怎么办 2个月婴儿感冒了怎么办 头发剪短了很丑怎么办 头发剪了后悔了怎么办 额头的碎头发翘怎么办 带耳机时间长耳朵疼怎么办