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

⭐算法OJ⭐汉明距离【位操作】(C++ 实现)Total 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。

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(n32)=O(n),其中 n n n 是数组的长度。
  • 空间复杂度: O ( 1 ) O(1) O(1),只使用了常数空间。

相关文章:

  • 【Python】Linux 升级 Python 版本(源码安装)
  • nginx中忽略已.开头的文件
  • 解锁 vue-property-decorator 的秘密:Vue 2 到 Vue 3 的 TypeScript 之旅!✨
  • 汇编语言 | 王爽 | 学习笔记
  • MambaTab:表格数据处理的新利器
  • linux Centos7 遗忘root用户密码
  • 计算机网络基础:NAT 网络地址转换
  • Java中队列(Queue)和列表(List)的区别
  • DICT领域有哪些重要的技术标准和规范?
  • MySQL开发陷阱与最佳实践:第1章:MySQL开发基础概述-1.2 MySQL开发环境搭建
  • C语言_数据结构总结9:树的基础知识介绍
  • 安卓投屏到mac操作
  • UE5 控件反射器查找源码方法
  • win32汇编环境,网络编程入门之二
  • Java与Elasticsearch集成详解,以及使用指南
  • [多线程]基于单例懒汉模式的线程池的实现
  • 使用Exchange Web Services(EWS)API实现发送Outlook邮件
  • 《C#上位机开发从门外到门内》3-1:串口调试助手
  • 卷积神经网络 - 卷积的互相关
  • 用Lua脚本实现Redis原子操作
  • 安徽省委常委、合肥市委书记费高云卸任副省长职务
  • 习近平举行仪式欢迎巴西总统卢拉访华
  • 石家庄推动城市能级与民生福祉并进
  • 冷冰川谈黑白
  • 气象干旱黄色预警继续:陕西西南部、河南西南部等地特旱
  • 庆祝上海总工会成立100周年暨市模范集体劳动模范和先进工作者表彰大会举行,陈吉宁寄予这些期待