Leetcode-477. Total Hamming Distance

前言:为了后续的实习面试,开始疯狂刷题,非常欢迎志同道合的朋友一起交流。因为时间比较紧张,目前的规划是先过一遍,写出能想到的最优算法,第二遍再考虑最优或者较优的方法。如有错误欢迎指正。博主首发CSDN,mcf171专栏。

博客链接:mcf171的博客

——————————————————————————————

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.

Note:

  1. Elements of the given array are in the range of to 10^9
  2. Length of the array will not exceed 10^4.
这个题目实质上就是找每一位有1的个数数多少,然后0的个数就是数组长度减去1个个数,每一位的组合数就是count_1 * count_0.

解法1:每次都同时计算所有数字的同一位,时间复杂度O(10^4 *  10^9 ),空间复杂度O(10 ^ 4)Your runtime beats 1.26% of java submissions.

public class Solution {
    public int totalHammingDistance(int[] nums) {
        int count = 0;
	List<Integer> data = new ArrayList<Integer>();
	for(int item : nums) data.add(item);
	while(data.size()!=0){
		count +=  diff(data,nums.length);
	}
	return count;
    }

    public int diff(List<Integer> nums, int totalNum){
	int count = 0;
	int count_1 = 0, count_0 = 0;
	for(int i = 0; i < nums.size(); ){
		int val = nums.get(i);
		if(val % 2 == 1) count_1 ++;
		val /= 2;
		if(val == 0)nums.remove(i);
		else{nums.set(i,val); i ++;}
	}
	count_0 = totalNum - count_1;
	count = count_1 * count_0;
	return count;
    }
}
解法2:用一个31位的数组来保存每一位1的数字,时间复杂度O(10^4 *  10^9 ),空间复杂度O(1) Your runtime beats 5.03% of java submissions.

public class Solution {
    public int totalHammingDistance(int[] nums) {
        int[] flags = new int[31];
        for(int item : nums){
            int index = 0;
            while(item != 0){
                if(item %2 != 0) flags[index] ++;
                index ++;
                item = item /2;
            }
        }
        int count = 0;
        for(int item : flags){
            count += item * (nums.length - item);
        }
        return count;
    }
}





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值