方法一:
思路:
(1)遍历数组nums,对每一个nums[i],求其余后面的每一个nums[j]的Hamming Distance。
(2)求x与y的Hamming Distance的方法:
---1)先求x^y的结果res。
---2)再依次求32位res的每一位与1进行与操作的结果,若不为0,则Hamming Distance加一。
public class Solution {
public int totalHammingDistance(int[] nums) {
int len = nums.length;
if (len == 0)
return 0;
int result = 0;
for (int i = 0; i < len - 1; i++) {
for (int j = i + 1; j < len; j++)
result += hammingDistance(nums[i], nums[j]);
}
return result;
}
public int hammingDistance(int x, int y) {
int res = x ^ y;
int count = 0;
for (int i = 0; i < 32; i++) {
if ((res & 1) != 0)
count++;
res >>= 1;
}
return count;
}
}
超时!!!
方法二:
思路:
(1)设置变量oneCount记录某一位上1的个数,result记录总的Hamming Distance。
(2)依次判断32位中的每一位。每判断完一位,右移一位继续判断下一位。
(3)针对每一位,遍历nums数组,判断每一个nums[j]的该位是否为1(nums[j]与1进行与操作得到的结果不是0则nums[j]的该位为1,oneCount加一)。
(4)遍历完nums数组后,oneCount * (len - oneCount)即为该位上的Hamming Distance,加到总结果result中。
public class Solution {
public int totalHammingDistance(int[] nums) {
int result = 0, oneCount = 0, len = nums.length;
for (int i = 0; i < 32; i++) {
oneCount = 0;
for (int j = 0; j < len; j++) {
if ((nums[j] & 1) != 0)
oneCount++;
nums[j] >>= 1;
}
result += (oneCount * (len - oneCount));
}
return result;
}
}
Runtime:45ms