⭐算法OJ⭐汉明距离【位操作】(C++ 实现)Total Hamming Distance
Hamming Distance(汉明距离)是用于衡量两个等长字符串在相同位置上不同字符的个数的度量。它通常用于比较两个二进制字符串或编码序列的差异。
定义
给定两个长度相同的字符串 A A A 和 B B B,它们的汉明距离 D ( A , B ) D(A,B) D(A,B) 是在相同位置上字符不同的位置的数量。
示例
- 二进制字符串:
- A=1011101
- B=1001001
- 汉明距离 D ( A , B ) = 2 D(A,B)=2 D(A,B)=2(第3位和第5位不同)。
- 字符串:
- A=“karolin”
- B=“kathrin”
- 汉明距离 D ( A , B ) = 3 D(A,B)=3 D(A,B)=3(第3、4、5位不同)。
应用
- 错误检测与纠正:在通信和编码理论中,汉明距离用于检测和纠正数据传输中的错误。
- 生物信息学:用于比较 DNA 序列的相似性。
- 机器学习:在分类算法中,用于计算样本之间的距离。
计算步骤
- 比较两个字符串的每一位。
- 统计不同位的数量。
- 返回统计结果作为汉明距离。
公式
对于长度为
n
n
n 的两个字符串
A
A
A 和
B
B
B,汉明距离为:
D
(
A
,
B
)
=
∑
i
=
1
n
δ
(
A
i
,
B
i
)
D(A,B)= ∑_{i=1}^n δ(A_i ,B_i)
D(A,B)=i=1∑nδ(Ai,Bi)
其中,
δ
(
A
i
,
B
i
)
δ(A_i ,B_i )
δ(Ai,Bi) 是指示函数,当
A
i
≠
B
i
A_i \neq B_i
Ai=Bi 时为1,否则为0。
191. Number of 1 Bits
Given a positive integer n
, write a function that returns the number of set bits in its binary representation (also known as the Hamming weight).
477. Total Hamming Distance
The Hamming distance between two integers is the number of positions at which the corresponding bits are different.
Given an integer array nums
, return the sum of Hamming distances between all the pairs of the integers in nums
.
Example 1:
Input: nums = [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).
The answer will be:
HammingDistance(4, 14) + HammingDistance(4, 2) + HammingDistance(14, 2) = 2 + 2 + 2 = 6.
Example 2:
Input: nums = [4,14,4]
Output: 4
C++ 实现
int totalHammingDistance(vector<int>& nums) {
int total = 0; // 总汉明距离
int n = nums.size(); // 数组长度
// 遍历每一位(0到31)
for (int i = 0; i < 32; i++) {
int count = 0; // 统计当前位为1的数的个数
for (int num : nums) {
// 检查当前位是否为1
if ((num >> i) & 1) {
count++;
}
}
// 当前位的贡献为 count * (n - count)
total += count * (n - count);
}
return total;
}
复杂度分析
- 时间复杂度: O ( n ⋅ 32 ) = O ( n ) O(n⋅32)=O(n) O(n⋅32)=O(n),其中 n n n 是数组的长度。
- 空间复杂度: O ( 1 ) O(1) O(1),只使用了常数空间。