当前位置: 首页 > news >正文

⭐算法OJ⭐汉明距离【位操作】(C++ 实现)Hamming Distance

Hamming Distance(汉明距离)是用于衡量两个等长字符串在相同位置上不同字符的个数的度量。它通常用于比较两个二进制字符串或编码序列的差异。

定义

给定两个长度相同的字符串 A A A B B B,它们的汉明距离 D ( A , B ) D(A,B) D(A,B) 是在相同位置上字符不同的位置的数量。

示例

  1. 二进制字符串:
    • A=1011101
    • B=1001001
    • 汉明距离 D ( A , B ) = 2 D(A,B)=2 D(A,B)=2(第3位和第5位不同)。
  2. 字符串:
    • 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=1nδ(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。

461. Hamming Distance

The Hamming distance between two integers is the number of positions at which the corresponding bits are different.
Given two integers x and y, return the Hamming distance between them.

Example 1:

Input: x = 1, y = 4
Output: 2
Explanation:
1   (0 0 0 1)
4   (0 1 0 0)↑   ↑
The above arrows point to positions where the corresponding bits are different.

Example 2:

Input: x = 3, y = 1
Output: 1

C++ 实现

int hammingDistance(int x, int y) {int xor_result = x ^ y;  // 异或操作int distance = 0;// 统计 xor_result 中 1 的个数while (xor_result != 0) {distance += xor_result & 1;  // 检查最低位是否为 1xor_result >>= 1;  // 右移一位}return distance;
}

复杂度分析

这个算法的时间复杂度为 O ( l o g n ) O(log\, n) O(logn),其中 n n nxy 的最大值。


http://www.mrgr.cn/news/94326.html

相关文章:

  • 【vue + JS】OCR图片识别、文字识别
  • 《基于大数据的营养果蔬推荐系统的设计与实现》开题报告
  • 在 Windows 上快速部署 OpenManus:从安装到运行
  • 计算机网络——DHCP实验
  • python -面试题--算法
  • RGV调度算法(三)--遗传算法
  • LeetCode 解题思路 15(Hot 100)
  • 独立开发记录:使用Trae和Cloudflare快速搭建了自己的个人博客
  • ES6回顾:闭包->(优点:实现工厂函数、记忆化和异步实现)、(应用场景:Promise的then与catch的回调、async/await、柯里化函数)
  • 【C#学习笔记04】C语言格式化输出
  • 深度剖析 Doris 数据倾斜,优化方案一网打尽
  • 【二分查找 寻找首端】P3718 [AHOI2017初中组] alter|普及+
  • uniapp实现 uview1 u-button的水波纹效果
  • 使用memmove优化插入排序
  • 新闻网页信息抽取
  • JVM 垃圾回收器的选择
  • 广播机制(Broadcasting)
  • 项目组织管理类型-职能式组织和矩阵式组织的区别
  • HOT100——二叉树篇Leetcode236. 二叉树的最近公共祖先
  • windows 下用docker 部署nginx