[leetcode, python] Total Hamming Distance 多个数字之间的汉明距离
来源:互联网 发布:合肥知茵女装 编辑:程序博客网 时间:2024/05/16 05:40
问题描述:
The Hamming distance between two integers is the number of positions at which the corresponding bits are different.Now your job is to find the total Hamming distance between all pairs of the given numbers.Example:Input: 4, 14, 2Output: 6Explanation: In binary representation, the 4 is 0100, 14 is 1110, and 2 is 0010 (justshowing 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.
解决方案:
class Solution(object): def totalHammingDistance(self, nums): """ :type nums: List[int] :rtype: int """ if len(nums)==0: return 0 else: # 将所有数字转换成的二进制字符串 nums_bin_str = [bin(item)[2:] for item in nums] # 以最长的二进制字符串为标准,将所有二进制字符串长度统一 len_num = [len(item) for item in nums_bin_str] max_len = max(len_num) append_len = [max_len-item for item in len_num] nums_bin_list = ['0'*item+nums_bin_str[i] for i,item in enumerate(append_len)] # 开始计算汉明距离 total_dist = 0 for i in range(max_len): # 每一列‘1’的个数乘以每一列‘0’的个数即为该列的汉明距离 col_list = [x[i] for x in nums_bin_list] one_dist = col_list.count('1') * col_list.count('0') # 将所有列的汉明距离相加即为总的汉明距离 total_dist += one_dist return total_dist
思路说明:
先统一二进制字符串的长度,形成一个矩阵;再计算矩阵每一列‘1’的个数乘以‘0’的个数的值,该值为该列的汉明距离;最后将每列的结果相加即为总的汉明距离。
0 0
- [leetcode, python] Total Hamming Distance 多个数字之间的汉明距离
- leetcode 477. Total Hamming Distance 任意两个数字的汉明距离之和
- [Leetcode,python] Hamming Distance 汉明距离
- LeetCode 477. Total Hamming Distance-python
- LeetCode: Total Hamming Distance
- LeetCode Total Hamming Distance
- leetcode-Total Hamming Distance
- [LeetCode]461. Hamming Distance(汉明距离)
- [LeetCode] Hamming Distance 汉明距离
- LeetCode -- Hamming Distance 汉明距离
- Leetcode--461. Hamming Distance汉明距离
- [LeetCode] Hamming Distance 汉明距离
- leetcode Hamming Distance 汉明距离
- LeetCode 461 Hamming Distance 汉明距离
- Leetcode 477. Total Hamming Distance 总海明距离 解题报告
- LeetCode 477. Total Hamming Distance
- 【Leetcode】477. Total Hamming Distance
- Leetcode Total Hamming Distance 477
- 想问一下iOS做游戏的多 还是应用的多?
- 安卓开机后 App自动启动 为什么在有些手机中启动不了?如何解决?
- 关于Drawable和BitmapDrawable得到的图片大小问题
- android.jar中没有ContextImpl类
- 初次安装AS启用模拟器后,弹出Enable VT-x in your BIOS security settings(refer to document for your computer)
- [leetcode, python] Total Hamming Distance 多个数字之间的汉明距离
- D3D11地形渲染教程五之TerrainTexture
- 笔记
- 新手,更新Android SDK Manager问题
- Linux中拷贝 cp命令中拷贝所有的写法
- 开发一进入程序就加载地图引起ANR 怎么办呢!!
- Android自定义Cursor
- LaTeX-数学公式中加粗字体
- 所有的Android属性都是未知的Intellij