477. Total Hamming Distance

此篇博客讲解如何通过编程解决一个实际问题:给定一个整数数组,求所有元素之间的汉明距离之和。算法涉及遍历每位、统计0和1的个数,并应用组合公式。适用于解决与二进制表示和离散数学有关的问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

Constraints:

  • 1 <= nums.length <= 104
  • 0 <= nums[i] <= 109
  • The answer for the given input will fit in a 32-bit integer.

给出的数字都在 32 位整数之内, 我们可以把每一位为 0 和为 1 的数字数量分别统计出来,假设为 0 的是 n 个, 那为 1 的就是 length - n 个, 那他们对整体距离的贡献就是 n * (length -n)


impl Solution {
    pub fn total_hamming_distance(nums: Vec<i32>) -> i32 {
        let mut total = 0;
        for i in 0..32 {
            let mut ones = 0;
            let mut zeros = 0;
            let mask = 1 << i;
            for j in 0..nums.len() {
                if nums[j] & mask > 0 {
                    ones += 1;
                } else {
                    zeros += 1;
                }
            }
            total += ones * zeros;
        }
        total
    }
}
好的,你的问题是如何基于给定的训练数据和测试数据构建K最近邻模型,并对测试数据进行分类预测。 首先,我们需要读取训练数据目录中的所有数字符号存储文件,并提取出文件名中的数字作为标签。然后,我们可以使用Levenshtein模块中的hamming函数计算每个训练数据文件与测试数据文件之间的汉明距离,找出与测试数据文件汉明距离最小的K个训练数据文件,并统计这K个训练数据文件中出现最多的标签作为测试数据的预测标签。 下面是一个简单的Python代码示例,用于实现K最近邻模型的训练和测试: ```python import os from Levenshtein import hamming # 读取训练数据 train_dir = 'trainingData' train_data = [] train_labels = [] for filename in os.listdir(train_dir): label = int(filename.split('_')[0]) train_labels.append(label) with open(os.path.join(train_dir, filename), 'r') as f: data = f.read().strip() train_data.append(data) # 定义K值和汉明距离函数 K = 5 def hamming_distance(a, b): return hamming(a, b) # 对每个测试数据进行分类预测 test_dir = 'testData' correct_count = 0 total_count = 0 for filename in os.listdir(test_dir): true_label = int(filename.split('_')[0]) with open(os.path.join(test_dir, filename), 'r') as f: test_data = f.read().strip() distances = [hamming_distance(test_data, d) for d in train_data] nearest_indices = sorted(range(len(distances)), key=lambda i: distances[i])[:K] nearest_labels = [train_labels[i] for i in nearest_indices] pred_label = max(set(nearest_labels), key=nearest_labels.count) if pred_label == true_label: correct_count += 1 else: print(f'Error: true label is {true_label}, but predicted label is {pred_label}.') total_count += 1 # 输出分类准确率 accuracy = correct_count / total_count print(f'Accuracy: {accuracy:.2%} ({correct_count}/{total_count})') ``` 以上代码中,我们首先读取训练数据目录中的所有数字符号存储文件,并提取出文件名中的数字作为标签,存储在train_labels列表中,训练数据存储在train_data列表中。 然后,我们定义了K值为5,并定义了一个hamming_distance函数,用于计算两个数据之间的汉明距离。 接下来,我们遍历测试数据目录中的所有文件,读取测试数据并计算与训练数据之间的汉明距离。我们找到与测试数据汉明距离最小的K个训练数据,并统计这K个训练数据中出现最多的标签作为测试数据的预测标签。如果预测标签与真实标签相同,则分类预测正确,否则输出错误信息。 最后,我们统计分类的准确率并输出结果。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值