【LeetCode-477】Total Hamming Distance
来源:互联网 发布:java反射的作用 编辑:程序博客网 时间:2024/05/21 18:44
题目:
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.
解题思路:使用暴力解决的方式超时了,不得不寻找更简单的方法,不卖官司了,直接说思路吧。
由于每一个数都是int型,因此每一个整数由32位组成,符号位由于都是正数,因此可以忽略,那剩下31位;
接下来建立一个大小为31的数组,分别存储第i位上为0的数的个数。
那么异或后第i位上1的个数 = 第i位上0的个数 * 第i位上1的个数,一共31位,最后做一个累加就好了。
public class TotalHammingDistance477 { public int totalHammingDistance(int[] nums) { if(nums == null || nums.length == 0) return 0; int res = 0, len = nums.length; int[] map = new int[31]; for(int i : nums) for(int j = 0; j < 31; j++) map[j] += (i & (1 << j)) == 0 ? 1 : 0; //map[i]为第i位为0的数量(该位1的数量 * 0的数量 = 异或后1的数量) for(int i = 0; i < 31; i++) res += map[i] * (len - map[i]); return res; }}
1 0
- 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
- sql server 什么是全外连接,左外连接,右外连接,它们的区别又是什么?
- Python 开发环境搭建与helloWorld 测试
- Java xml解析(DOM、SAX)
- 深入理解Java:注解(Annotation)自定义注解入门
- WCF发布到IIS
- 【LeetCode-477】Total Hamming Distance
- Android-System类
- Installing Spark Guid (1)
- 操作系统精髓与设计原理-进程描述和控制
- 在Java中对mysql数据库插入datetime类型数据
- 今日开始写博客,一个礼拜最少两篇
- 内连接与左右连接
- 编写一个程序,它打开一个文本文件,逐个字符地读取该文件,直到到达文件末尾,然后指出该文件中包含多少个字符
- QT 用流读写二进制文件解决高低端问题