题目:

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. Picture intermediate frame ----- increase smooth

    By YutaiHou

  2. iOS - 对UIColor颜色反差

    iOS中默认的很多方法可以获得不同种颜色的UIColor对象,但是White和Black等灰度值其实是用灰阶透明度调制 +colorWithWhite:alpha:,这些CGColorRef拥有2个组 ...

  3. BZOJ4700: 适者

    先排序,枚举删一个点,在前面找出最优的另一个点,容易推出斜率方程,平衡树维护凸包. #include<bits/stdc++.h> using namespace std; typedef ...

  4. http与https的区别

    HTTPhttp是一个应用层协议,由请求和响应构成,是一个标准的客户端服务器模型.http通常承载于TCP之上,有时也承载于TLS或SSL协议层之上,这就是常说的httphttp 无状态协议,同一个客 ...

  5. web页面之响应式布局

    一.什么是响应式布局? 响应式布局是Ethan Marcotte在2010年5月份提出的一个概念,简而言之,就是一个网站能够兼容多个终端——而不是为每个终端做一个特定的版本.这个概念是为解决移动互联网 ...

  6. Java学习笔记14---使用标志位控制循环

    使用标志位控制循环 前面提到了控制循环的常用技术:计数器控制的循环.另一种控制循环的常用技术是在读取和处理一个集合的值时指派一个特殊值.这个特殊的输入值也成为标志值(sentinel value),用 ...

  7. Oracle函数组的使用

    --1.组函数--COUNT():用来统计记录的条数 如果没有记录,返回 0--COUNT函数可以根据一列或多列进行计算,没有排重功能--统计EMP表一共有多少条记录select count(empn ...

  8. PopupWindow 使用

    昨天马失前蹄,为了做一个小键盘,耽误了两个小时,记录一下心路历程 1.关于需求与选择 需求: 点击一个按钮,弹出一个小键盘(类似于输入法键盘) 选择: (1)方案一:KeyboardView 这是百度 ...

  9. Wix打包技术学习笔记

    http://blog.csdn.net/duanzilin/article/details/5951709 很好的教程,有时间好好学习一下.然后自己整理笔记,暂时不打算深入研究

  10. 第四篇 基于.net搭建热插拔式web框架(RazorEngine实现)

    在开头也是先给大家道个歉,由于最近准备婚事导致这篇文章耽误了许久,同时也谢谢老婆大人对我的支持. 回顾上篇文章,我们重造了一个controller,这个controller中用到了视图引擎,我们的视图 ...