【Leetcode】477. Total Hamming Distance

方法一:

思路:

(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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值