算法练习笔记(十七)——汉明距离的计算

来源:互联网 发布:淘宝借贷延期 编辑:程序博客网 时间:2024/06/05 11:13

汉明距离指的是两个数字在二进制的情况之下,相互转化要经过几位的变换

题目地址:https://leetcode.com/problems/total-hamming-distance/#/description

题目: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, 2Output: 6Explanation: In binary representation, the 4 is 0100, 14 is 1110, and 2 is 0010 (justshowing 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.
解答:

1.运用哈希将每一个数的二进制换算出来再进行位和位之间的计算

class Solution {public:    unordered_map<int, vector<int> >map;    int totalHammingDistance(vector<int>& nums) {        int size = nums.size();        for(int i = 0; i < size; i ++){            int key = nums[i];            if(key == 0)map[key].push_back(0);            if(map[key].size() > 0)continue;            while(key != 0){                int s = key % 2;                map[nums[i]].push_back(s);                key = key/2;            }        }        int count = 0;        for(int i = 0; i < size; i ++)            for(int j = i + 1; j < size; j ++){                count += dis(nums[i], nums[j]);            }        return count;    }    int dis(int a, int b){        if(a == b) return 0;        int count = 0;        int sa = map[a].size();        int sb = map[b].size();        int key = max(sa, sb);        for(int i = 0; i < key; i ++){            if(!map[a][i] && map[b][i])                if(map[b][i] == 1)count ++;            if(map[a][i] && !map[b][i])                if(map[a][i] == 1)count ++;            if(map[a][i] && map[b][i])                if(map[a][i] != map[b][i])count ++;        }        return count;            }};

2.对于每个数字,进行一位一位的二进制遍历,得到这一位是1的数目以及0的数目,再计算出互相变换的开销,再叠加

class Solution {public:    int totalHammingDistance(vector<int>& nums) {        int size = nums.size();        if(size < 2) return 0;        int ans = 0;        int *zeroOne = new int[2];        while(true)        {            int zeroCount = 0;            zeroOne[0] = 0;            zeroOne[1] = 0;            for(int i = 0; i < nums.size(); i++)            {                if(nums[i] == 0) zeroCount++;                zeroOne[nums[i] % 2]++;                nums[i] = nums[i] >> 1;            }            ans += zeroOne[0] * zeroOne[1];            if(zeroCount == nums.size()) return ans;        }    }};


阅读全文
0 0
原创粉丝点击