爨爨爨好

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

▶ 与 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 };

 

posted on 2018-01-21 00:00  爨爨爨好  阅读(150)  评论(0编辑  收藏  举报