LeetCode 题解工作台

汉明距离总和

两个整数的 汉明距离 指的是这两个数字的二进制数对应位不同的数量。 给你一个整数数组 nums ,请你计算并返回 nums 中任意两个数之间 汉明距离的总和 。 示例 1: 输入: nums = [4,14,2] 输出: 6 解释: 在二进制表示中,4 表示为 0100 ,14 表示为 1110 ,…

category

3

题型

code_blocks

6

代码语言

hub

3

相关题

当前训练重点

中等 · 数组·数学

bolt

答案摘要

我们在 $[0, 31]$ 的范围内枚举每一位,对于当前枚举的位 ,我们统计所有数字中的第 位为 的个数 ,那么这些数字中的第 位为 的个数就是 $b = n - a$,其中 是数组的长度。这样的话,在第 位上的汉明距离之和就是 $a \times b$,我们把所有的位的汉明距离相加即为答案。 时间复杂度 $O(n \times \log M)$,其中 和 分别是数组的长度和数组中…

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数组·数学 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

两个整数的 汉明距离 指的是这两个数字的二进制数对应位不同的数量。

给你一个整数数组 nums,请你计算并返回 nums 中任意两个数之间 汉明距离的总和

 

示例 1:

输入:nums = [4,14,2]
输出:6
解释:在二进制表示中,4 表示为 0100 ,14 表示为 1110 ,2表示为 0010 。(这样表示是为了体现后四位之间关系)
所以答案为:
HammingDistance(4, 14) + HammingDistance(4, 2) + HammingDistance(14, 2) = 2 + 2 + 2 = 6

示例 2:

输入:nums = [4,14,4]
输出:4

 

提示:

  • 1 <= nums.length <= 104
  • 0 <= nums[i] <= 109
  • 给定输入的对应答案符合 32-bit 整数范围
lightbulb

解题思路

方法一:位运算

我们在 [0,31][0, 31] 的范围内枚举每一位,对于当前枚举的位 ii,我们统计所有数字中的第 ii 位为 11 的个数 aa,那么这些数字中的第 ii 位为 00 的个数就是 b=nab = n - a,其中 nn 是数组的长度。这样的话,在第 ii 位上的汉明距离之和就是 a×ba \times b,我们把所有的位的汉明距离相加即为答案。

时间复杂度 O(n×logM)O(n \times \log M),其中 nnMM 分别是数组的长度和数组中的元素的最大值。空间复杂度 O(1)O(1)

1
2
3
4
5
6
7
8
9
class Solution:
    def totalHammingDistance(self, nums: List[int]) -> int:
        ans, n = 0, len(nums)
        for i in range(32):
            a = sum(x >> i & 1 for x in nums)
            b = n - a
            ans += a * b
        return ans
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    The candidate should demonstrate familiarity with bit manipulation and array traversal.

  • question_mark

    Look for an understanding of time complexity optimization when discussing larger input sizes.

  • question_mark

    Expect the candidate to recognize the inefficiencies of a brute force solution and propose an optimized approach.

warning

常见陷阱

外企场景
  • error

    Misunderstanding the definition of Hamming distance and incorrectly comparing non-corresponding bits.

  • error

    Failure to optimize the brute force solution, resulting in an inefficient approach for larger arrays.

  • error

    Incorrect handling of edge cases, such as arrays with very small or very large values.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Calculate Hamming distance for a fixed number of integers instead of all pairs.

  • arrow_right_alt

    Modify the problem to calculate the Hamming distance between a given set of numbers and a target number.

  • arrow_right_alt

    Optimize for extremely large arrays, aiming for constant time solutions based on preprocessed bit counts.

help

常见问题

外企场景

汉明距离总和题解:数组·数学 | LeetCode #477 中等