算法练习笔记(十七)——汉明距离的计算
来源:互联网 发布:淘宝借贷延期 编辑:程序博客网 时间: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:
- Elements of the given array are in the range of
0
to10^9
- 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
- 算法练习笔记(十七)——汉明距离的计算
- 小练习:计算汉明距离
- 算法练习笔记(15)—— 哈希表的练习
- 计算两点之间的距离(笔记)
- 计算编辑距离的算法
- 机器学习笔记(十七)——EM算法的推导
- 赛码网练习——小球的距离
- 算法练习笔记(十三)——图的克隆
- 汉明距离计算
- 经纬度计算他们距离的算法(!!!!!!!!!求助啊)
- 汉明距离的计算代码
- 算法练习笔记(五)— 图
- PAT算法笔记(十七)————月饼
- 《编程之美》学习笔记——计算字符串的距离
- Atitti knn实现的具体四个距离算法 欧氏距离、余弦距离、汉明距离、曼哈顿距离
- 初始化—Swift学习笔记(十七)
- [算法]计算编辑距离
- 算法练习笔记(三)— 分治算法
- HDU 1073 Online Judge(水~)
- 多个".h"文件中声明及定义 全局变量和函数
- oracle驱动加载的区别
- tensorflow学习笔记(1):编程风格,基本原理,入门教程(更新中...)
- 微信小程序大全:767个小程序
- 算法练习笔记(十七)——汉明距离的计算
- Java基础算法练习五题——(4)
- 【命名规范】C++命名规范约定
- HTML5 新标签和属性(video)
- session和cookie
- 判断JS对象是否为Array
- 树莓派raspberry pi 安装远程工具teamviewer
- Jemeter的Http请求超时设置及其他
- JQuery UI----初次学习(添加关于添加UI包的顺序与dialog属性设置)