[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;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_28033719/article/details/107150716