zoukankan      html  css  js  c++  java
  • 461. Hamming Distance + 477. Total Hamming Distance

    ▶ 与 Hamming  距离相关的两道题。

    ▶ 461. 求两个数 x 与 y 的哈夫曼距离。

    ● 代码,4 ms,对 x 和 y 使用异或,然后求值为 1 的位的个数。

     1 class Solution
     2 {
     3 public:
     4     int hammingDistance(int x, int y)
     5     {
     6         int i,temp;
     7         for (i = 0, temp = x ^ y; temp > 0; temp &= temp - 1, i++); 
     8         return i;
     9     }
    10 };

    ● 代码,7 ms,转化为 bitset 来逐位比较。

     1 class Solution
     2 {
     3 public:
     4     int hammingDistance(int x, int y)
     5     {
     6         bitset<32> xBS(x), yBS(y);
     7         int i, count;
     8         for (i = count = 0; i < 32; i++)
     9             count += (xBS[i] != yBS[i]);
    10         return abs(count);
    11     }
    12 };

    ▶ 477. 求数组 nums 中,所有数字之间两两哈夫曼距离的和。

    ● 代码,56 ms 。逐位计数计算。把所有数并排放,研究每一位上的 1 有多少个,求其两两异或的结果,如一共有 12 个数,某一位上共 7 个 1,则该位对哈夫曼距离的贡献为 C71C51 = 35 。枚举所有数对进行计算的方法超时了。

     1 class Solution
     2 {
     3 public:
     4     int totalHammingDistance(vector<int>& nums)
     5     {
     6         int i, j, one, n, output; 
     7         for (i = output = 0, n = nums.size(); i < 32; i++)
     8         {
     9             one = 0;
    10             for (j = 0; j < n; j++)
    11                 one += (nums[j] >> i) & 1;
    12             output += one * (n - one);
    13         }
    14         return output;
    15     }
    16 };
  • 相关阅读:
    pe文件结构
    dll
    术语
    创建内存映射文件
    函数的调用约定
    串口
    linux 之 tcpdump
    linux 之程序管理
    perl 之eval
    2020-10-27_组合快捷键
  • 原文地址:https://www.cnblogs.com/cuancuancuanhao/p/8322409.html
Copyright © 2011-2022 走看看