Total Hamming Distance
来源:互联网 发布:mac os 10.7软件推荐 编辑:程序博客网 时间:2024/06/16 20:29
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.解析:首先想到的是每对数进行异或,然后求取异或后中1的个数,这个时间复杂度为
O(n^2),超时,后来知道因为每位数都要进行比较,所以直接求取每位数中为1的数有多少,然后跟为0的个数相乘即是这个位的Hamming Distance.
代码:
class Solution {public: int totalHammingDistance(vector<int>& nums) { /* int N=nums.size(); int ans=0; for (int i=0; i<N; i++) { for (int j=i+1; j<N; j++) { int temp=nums[i]^nums[j]; ans+=Numberof1(temp); } } return ans; } int Numberof1(int n) { int count=0; while(n) { ++count; n=(n-1)&n; } return count; }*/ int N=nums.size(); int ans=0; for (int i=0; i<32; i++) { int numcount=0; for (int j=0; j<N; j++) { numcount+=((nums[j]>>i)&1); } ans+=(numcount*(N-numcount)); } return ans; }};
0 0
- hihocoder # Total Hamming Distance
- 477. Total Hamming Distance
- 477. Total Hamming Distance
- 477. Total Hamming Distance
- 477. Total Hamming Distance**
- LeetCode: Total Hamming Distance
- LeetCode Total Hamming Distance
- Total Hamming Distance
- 477. Total Hamming Distance
- 477. Total Hamming Distance
- 477. Total Hamming Distance
- 477. Total Hamming Distance
- 477. Total Hamming Distance
- 477. Total Hamming Distance
- leetcode-Total Hamming Distance
- 477. Total Hamming Distance
- 477. Total Hamming Distance
- LeetCode 477. Total Hamming Distance
- 【Java 并发】详解 ThreadLocal
- 处理 python 无法抓取 HTTPS 请求
- 34. Search for a Range
- java-jpa-criteriaBuilder使用入门
- 【IOS学习之常见问题】 Program License Agreement updated,The 'Apple Developer Program License Agreement' has b
- Total Hamming Distance
- 用commons-fileupload实现文件上传
- [[DobbyBlok alloc] init];
- JavaFX8 modena样式(css)源码
- APP安全报告第四期:如果共享单车APP会泄漏敏感信息,你还会用吗?
- 链表排序——插入排序(纯C语言版)
- spring集成redis及简单使用
- Notification的使用以及Intent打开各种文件
- Myeclipse2015下载github上项目到本地(图解)