[leetcode]477. Total Hamming Distance
Analysis
等国庆等国庆!!!!!—— [每天刷题并不难]
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.
计算一个数组里的数字的Hamming Distance总和。
Implement
方法一(暴力,会超时)
class Solution {
public:
int totalHammingDistance(vector<int>& nums) {
int res = 0;
int len = nums.size();
for(int i=0; i<len-1; i++){
for(int j=i+1; j<len; j++)
res += HD(nums[i], nums[j]);
}
return res;
}
int HD(int num1, int num2){
int res = 0;
for(int i=0; i<32; i++){
if((num1 & (1<<i)) ^ (num2 & (1<<i)))
res++;
}
return res;
}
};
方法二(先统计数组中的数在某一位上为1的个数,那么在这一位的海明距离就是为1的个数乘以为0的个数,然后依次统计出32位上的海明距离,最后相加得到结果)
class Solution {
public:
int totalHammingDistance(vector<int>& nums) {
int res = 0;
int len = nums.size();
for(int i=0; i<32; i++){
int cnt = 0;
for(auto num:nums){
if(num & (1<<i))
cnt++;
}
res += cnt*(len-cnt);
}
return res;
}
};