题目:

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:

Input: x = 1, y = 4
Output: 2
Explanation:
1 (0 0 0 1)
4 (0 1 0 0)
↑ ↑
The above arrows point to positions where the corresponding bits are different.

Example:

Input: 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). So the answer will be:
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补足和长的相同位数。

   def hammingDistance(self, x, y):
"""
:type x: int
:type y: int
:rtype: int
"""
str1 = bin(x)[2:]
str2 = bin(y)[2:]
if len(str1) < len(str2):
str1 = ''*(abs(len(str2)-len(str1)))+str1
else:
str2 = '' * (abs(len(str2) - len(str1))) + str2 res = 0
for i in range(0,len(str1)):
if not str1[i:i+1] == str2[i:i+1]:
res += 1
return res

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

 def totalHammingDistance(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums:
return 0
res = 0
new_nums = sorted(nums)
print sorted(set(nums))
for i in range(len(new_nums)):
for j in new_nums[i+1:]:
print new_nums[i],j
print self.hammingDistance(new_nums[i],j)
res += self.hammingDistance(new_nums[i],j)
return res

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

    def totalHammingDistance2(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums:
return 0
res = 0
lists = []
nums.sort()
for i in nums:
temp = list(bin(i)[2:])
temp.reverse()
lists.append(temp) for i in range(len(lists[-1])):
count_0, count_1 = 0, 0
for element in lists:
# print element
if len(element)-1 < i:
count_0 += 1
elif element[i] == '':
count_0 += 1
elif element[i] == '':
count_1 += 1
# print count_0,count_1
res += count_0 * count_1
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. 架构师养成记--6.单例和多线程、ThreadLocal

    一.ThreadLocal 使用wait/notify方式实现的线程安全,性能将受到很大影响.解决方案是用空间换时间,不用锁也能实现线程安全. 来看一个小例子,在线程内的set.get就是thread ...

  2. &#65279导致页面顶部空白一行解决方法 【】

    2016年11月7日10:57:10 模板文件生成html文件之后会在body开头处加入一个可见的控制符&#65279,导致页面头部会出现一个空白行.原因是页面的编码是UTF-8 + BOM. ...

  3. python常用模块(模块和包的解释,time模块,sys模块,random模块,os模块,json和pickle序列化模块)

    1.1模块 什么是模块: 在计算机程序的开发过程中,随着程序代码越写越多,在一个文件里代码就会越来越长,越来越不容易维护. 为了编写可维护的代码,我们把很多函数分组,分别放到不同的文件里,这样,每个文 ...

  4. C3P0连接池配置和实现详解

    一.配置 <c3p0-config> <default-config> <!--当连接池中的连接耗尽的时候c3p0一次同时获取的连接数.Default: 3 --> ...

  5. git rebase

    git rebase -i HEAD~[number_of_commits] git rebase -i HEAD~2

  6. [Java] JSP笔记 - 自定义标签

    自定义标签的创建步骤: 自定义标签的四大功能: 自定义标签的类结构: 在 1.0 中呢, 可以将 <body-content> 的值设置为 JSP, 2.0中则不允许在自定义标签体中出现j ...

  7. tomcat用root权限也起不来

    昨晚把服务器弄的启动不了了,先来还原一下作案现场, 错误操作过程:替换classes目录下的某个目录,比如com,由于替换了classes文件,所以需要重启tomcat,在bin目录下执行sh sta ...

  8. Ubuntu GNURadio gr-Radar 的安装

    1.安装Ubuntu 进行磁盘管理,设置不少于50G的未分配空间 使用rufus-2.8制作Ubuntu 16.4安装盘 保持U盘插入,重启电脑,开机时进入BIOS设置从该安装盘启动并安装 2.激活w ...

  9. Activiti5.10简易教程一

    Activiti5.10简易教程一 一搭建环境 1.1   JDK 6+ activiti 运行在版本 6 以上的 JDK 上.转到 Oracle Java SE 下载页面,点击按钮“下载 JDK ” ...

  10. NOSDK--关于android傻瓜式的分包设想

    一直以来,我总是以“够用就好”为理由,很少再维护过自己的一键打包的项目.最近接触了棱镜的sdk,感觉将apk包上传到棱镜服务器,后台来进行分包这种简单的方式很招人待见. 原理似乎不难,apk即zip压 ...