leetcode 477 Total Hamming Distance
来源:互联网 发布:英语在线交流软件 编辑:程序博客网 时间:2024/05/18 00:23
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 0 to 10^9
2. Length of the array will not exceed 10^4.
本题难度在leetcode上标记为medium,其实并不难,关键是不要被total迷惑住,把握住hamming distance的定义就好。
关于 hamming distance:两个数各二进制位置上的不同位个数的总和。
只求两个数的海明距离简单异或即可得到答案,本题只要把异或过程拆开即可求解,类似之前做过的一道题目,那道题是求一个数组里的两个不同数分别是多少,关键的一步是利用不同数的二进制表达的最低位开始的某一位不同(0和1),凭借这一位将数组分为两堆,分别异或求解。
对于本题:
要求任意两个数的海明距离,根据上面的分析,海明距离是不同位的个数求和,对于数组中数的每一位,我们都可以把它分成两组,一组该位是0 另一组为1,对于每一位的分别求解,就可以得到对于该位上所有数的海明距离之和,最后将各位求和结果再求和,就得到了最终解。
实现代码如下(C++11):
class Solution {
public:
int totalHammingDistance(vector& nums) {
int total = 0; int size = nums.size(); for(int i = 0;i<32;i++) { int count = 0; for(auto&val:nums) { if((val>>i)&1) count++; } total+= count*(size-count); } return total;}
};
`
- Leetcode Total Hamming Distance 477
- 【LeetCode-477】Total Hamming Distance
- leetcode-477-Total Hamming Distance
- leetcode 477 Total Hamming Distance
- Leetcode 477 Total Hamming Distance
- LeetCode.477 Total Hamming Distance
- LeetCode: Total Hamming Distance
- LeetCode Total Hamming Distance
- leetcode-Total Hamming Distance
- leetcode 477 Total Hamming Distance C++
- LeetCode 477. Total Hamming Distance
- 【Leetcode】477. Total Hamming Distance
- LeetCode 477. Total Hamming Distance
- [leetcode] 477. Total Hamming Distance
- LeetCode 477. Total Hamming Distance
- LeetCode 477. Total Hamming Distance
- LeetCode 477. Total Hamming Distance
- Leetcode-477. Total Hamming Distance
- Eclipse下Java Resources报红叉问题
- log4cplus应用之日志文件输出(三)
- 第六届蓝桥杯加法变乘法
- 一、swift3.0简介
- IDEA 常用配置 和插件
- leetcode 477 Total Hamming Distance
- 第5节 分析system_call中断处理过程【Linux内核分析】
- Android事件分发机制源码分析上----View事件分发分析
- intellij nginx server 配置
- 设计模式-全局观
- java学习笔记3.24
- 怎么给github上传代码:一步上传代码到github
- HDU 5410 CRB and His Birthday(01+完全)
- Iterator和ListIterator