题目:

The Hamming distance between two integers is the number of positions at which the corresponding bits are different.

Given two integers x and y, calculate the Hamming distance.

Note:
0 ≤ xy < 231.

Example:

  1. Input: x = 1, y = 4
  2. Output: 2
  3. Explanation:
  4. 1 (0 0 0 1)
  5. 4 (0 1 0 0)

  6. The above arrows point to positions where the corresponding bits are different.

Example:

  1. Input: 4, 14, 2
  2. Output: 6
  3. Explanation: In binary representation, the 4 is 0100, 14 is 1110, and 2 is 0010 (just
  4. showing the four bits relevant in this case). So the answer will be:
  5. HammingDistance(4, 14) + HammingDistance(4, 2) + HammingDistance(14, 2) = 2 + 2 + 2 = 6.

Note:

  1. Elements of the given array are in the range of to 10^9
  2. Length of the array will not exceed 10^4

代码:

这两周比较慢,都没有做题,赶紧做两道。这两个题目比较像,就放在一起吧。汉明距离,就是把数字变成二进制,看有多少为不一样,不一样的个数就是汉明距离。

所以,第一题,仅仅比较两个数字,我就用了常人都能想到的方法,转换成二进制字符串,遍历比较。唯一注意的就是将较短的字符串前面加0补足和长的相同位数。

  1. def hammingDistance(self, x, y):
  2. """
  3. :type x: int
  4. :type y: int
  5. :rtype: int
  6. """
  7. str1 = bin(x)[2:]
  8. str2 = bin(y)[2:]
  9. if len(str1) < len(str2):
  10. str1 = ''*(abs(len(str2)-len(str1)))+str1
  11. else:
  12. str2 = '' * (abs(len(str2) - len(str1))) + str2
  13.  
  14. res = 0
  15. for i in range(0,len(str1)):
  16. if not str1[i:i+1] == str2[i:i+1]:
  17. res += 1
  18. return res

这个题通过了,但第二个题目要求给出一个字符串,两两求出汉明距离,然后相加。于是,我接着上题的函数,增加了一个遍历,O(n^2):

  1. def totalHammingDistance(self, nums):
  2. """
  3. :type nums: List[int]
  4. :rtype: int
  5. """
  6. if not nums:
  7. return 0
  8. res = 0
  9. new_nums = sorted(nums)
  10. print sorted(set(nums))
  11. for i in range(len(new_nums)):
  12. for j in new_nums[i+1:]:
  13. print new_nums[i],j
  14. print self.hammingDistance(new_nums[i],j)
  15. res += self.hammingDistance(new_nums[i],j)
  16. return res

逻辑是没错,但不用想,leetcode中当然超时,会有一个包含1000个7、8位数字的列表去测试。唉,没办法,想不出来,百度了一下。这个汉明距离,其实可以通过每个bit位上面数字0的个数和1的个数相乘的结果,相加求得。等于逐一遍历列表中每个数字的每个bit位,所有bit位遍历一遍。

  1. def totalHammingDistance2(self, nums):
  2. """
  3. :type nums: List[int]
  4. :rtype: int
  5. """
  6. if not nums:
  7. return 0
  8. res = 0
  9. lists = []
  10. nums.sort()
  11. for i in nums:
  12. temp = list(bin(i)[2:])
  13. temp.reverse()
  14. lists.append(temp)
  15.  
  16. for i in range(len(lists[-1])):
  17. count_0, count_1 = 0, 0
  18. for element in lists:
  19. # print element
  20. if len(element)-1 < i:
  21. count_0 += 1
  22. elif element[i] == '':
  23. count_0 += 1
  24. elif element[i] == '':
  25. count_1 += 1
  26. # print count_0,count_1
  27. res += count_0 * count_1
  28. return res

试了下,果然没问题!:)

461. Hamming Distance and 477. Total Hamming Distance in Python的更多相关文章

  1. [LeetCode] 477. Total Hamming Distance 全部汉明距离

    The Hamming distance between two integers is the number of positions at which the corresponding bits ...

  2. 477. Total Hamming Distance总的二进制距离

    [抄题]: The Hamming distance between two integers is the number of positions at which the correspondin ...

  3. [LeetCode] 477. Total Hamming Distance(位操作)

    传送门 Description The Hamming distance between two integers is the number of positions at which the co ...

  4. 【LeetCode】477. Total Hamming Distance 解题报告(Python & C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 位运算 日期 题目地址:https://leetco ...

  5. 461. Hamming Distance + 477. Total Hamming Distance

    ▶ 与 Hamming  距离相关的两道题. ▶ 461. 求两个数 x 与 y 的哈夫曼距离. ● 代码,4 ms,对 x 和 y 使用异或,然后求值为 1 的位的个数. class Solutio ...

  6. LeetCode "477. Total Hamming Distance"

    Fun one.. the punch line of this problem is quite common in Bit related problems on HackerRank - vis ...

  7. 477. Total Hamming Distance

    class Solution { public: int totalHammingDistance(vector<int>& nums) { ; ; i < ; i++) { ...

  8. 477 Total Hamming Distance 汉明距离总和

    两个整数的 汉明距离 指的是这两个数字的二进制数对应位不同的数量.计算一个数组中,任意两个数之间汉明距离的总和.示例:输入: 4, 14, 2输出: 6解释: 在二进制表示中,4表示为0100,14表 ...

  9. [LeetCode] Total Hamming Distance 全部汉明距离

    The Hamming distance between two integers is the number of positions at which the corresponding bits ...

随机推荐

  1. jquery中ajax用return来返回值无效

    jquery中,ajax返回值,有三种写法,只有其中一种是成功的 /** * async:false,同步调用 * 返回1:2 * 失败 * 分析:ajax内部是一个或多个定义的函数,ajax中ret ...

  2. 记一周cdqz训练

    #include <cstdio> using namespace std; int main(){ puts("转载请注明出处:http://www.cnblogs.com/w ...

  3. c# 判断访问来源是否来自手机

    public Boolean IsMobileDevice() { string[] mobileAgents =new []{ "iphone", "android&q ...

  4. bat基础

    首先所有命令在cmd命令行中都能找到说明: 例如 想知道type用法 输入type /? 其他命令都一样 type [drive:][path] filename 显示文本文件内容 虽然有点鸡肋 1 ...

  5. 矢量图绘制工具Svg-edit调整画布的大小

    矢量图绘制工具Svg-edit调整画布的大小 ------------------------------ ------------------------

  6. Netty源码分析之客户端启动过程

    一.先来看一下客户端示例代码. public class NettyClientTest { public void connect(int port, String host) throws Exc ...

  7. 学习篇:TypeCodes的2015年博客升级记

    原文: https://typecodes.com/mix/2015updateblog.html 2015年博客升级记 作者:vfhky | 时间:2015-05-23 17:25 | 分类:mix ...

  8. ip扫描

    ipscan24 Advanced IP Scanner http://www.advanced-ip-scanner.com/cn/

  9. 深入理解javascript原型和闭包 (转)

    该教程绕开了javascript的一些基本的语法知识,直接讲解javascript中最难理解的两个部分,也是和其他主流面向对象语言区别最大的两个部分--原型和闭包,当然,肯定少不了原型链和作用域链.帮 ...

  10. 视图控制器的View整体上移问题

    最近我朋友代码出现一个问题,我看了下,发现已经是适配iOS那时候的问题了 如果你准备将你的老的 iOS 6 app 迁移到 iOS 7 上,那么你必须注意了.当你的老的 app 在 iOS 7 设备上 ...