[Leetcode学习-java]Total Hamming Distance(所有int的汉明距离)

问题:

难度:medium

说明:

给一个int[] arr,求数组所有整形的 位元 汉明距离,汉明距离是指两个等长字符串之间不同的字符个数,题目就要求写出数组每两个32位int不同的位元个数。

问题链接:https://leetcode.com/problems/total-hamming-distance/

相关算法:

Edit Distance(编辑距离):https://blog.csdn.net/qq_28033719/article/details/106472232

Hamming Distance(int的汉明距离):https://blog.csdn.net/qq_28033719/article/details/107149694

输入范围:

Elements of the given array are in the range of 0 to 10^9
Length of the array will not exceed 10^4.

输入案例:

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.

我的代码:

我看了下其他提示,就大概明白了,如果用dp直接做 32 * 10 ^ 4 ^ 2 肯定超时,所以通过32位位元做,可以得到 O(N) 时间复杂度:

1、首先统计每个位元有多少的 1 数量

 

2、然后根据规律

当数组该处位元有 2 个 0,1 个 1 的时候 (0 0 1),汉明距离为:
d = (1 * 1) + (1 * 1) = 2

当数组该处位元有 3 个 0,1 个 1 的时候 (0 0 0 1),汉明距离为:
d = (1 * 1) + (1 * 1) + (1 * 1) = 3

当数组该处位元有 2 个 0,2 个 1 的时候 (0 0 1 1),汉明距离为:
d = (1 * 2) + (1 * 2) = 4

当数组该处位元有 3 个 0,2 个 1 的时候 (0 0 0 1 1),汉明距离为:
d = (1 * 2) + (1 * 2)  + (1 * 2) = 6

当数组该处位元有 2 个 0,3 个 1 的时候 (0 0 1 1 1),汉明距离为:
d = (1 * 3) + (1 * 3) = 6

当数组该处位元有 3 个 0,3 个 1 的时候 (0 0 0 1 1 1),汉明距离为:
d = (1 * 3) + (1 * 3) + (1 * 3) = 9

那么数组长为 L,该处有 N 个 1 的时候,相当于有(L - N)个0,该位元汉明距离应该是: (L - N) * N

class Solution {
    public int totalHammingDistance(int[] nums) {
        int len = nums.length;
        int count = 0;

        for(int i = 0;i < 32;i ++) {
            // 把每个位元的 1 统计出来
            int total = 0;
            for(int j = 0;j < len;j ++)
                total += (nums[j] >> i) & 1;
            // (L - N) * N
            count += (len - total) * total;
        }
        return count;
    }
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值