【12月19日】LeetCode刷题日志(二):Hamming Distance
来源:互联网 发布:建立数据库的意义 编辑:程序博客网 时间:2024/06/03 16:46
package com.njust.med.totalhammingdistance;/** * 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. * leecode上关于汉明距离的题目很多。汉明距离:汉明距离是使用在数据传输差错控制编码里面的,汉明距离是一个概念,它表示两个 *(相同长度)字对应位不同的数量,我们以d(x,y)表示两个字x,y之间的汉明距离。对两个字符串进行异或运算,并统计结果为1的个数,那么这个数就是汉明距离。 * 思路1:利用在easy中的hammingdistace进行计算-->此思路在测试集运行到哦最后一个的时候超时 * * 思路2:leetcode上的高票答案 -- 厉害 * 数组里面的元素都看成是一个32位二进制;逐位进行统计。 * 例如,先统计第一位上所有元素的值,令nums数组中所有元素的第一位中,有bitCount个1,对应的有n-bitCount个0, * 仅根据以上信息就可以推断这些差异会对hamming距离贡献bitCount*(n - bitCount) * * * public int totalHammingDistance(int[] nums) { * int total = 0, n = nums.length; * for (int j=0;j<32;j++) { * int bitCount = 0; * for (int i=0;i<n;i++) * bitCount += (nums[i] >> j) & 1; * total += bitCount*(n - bitCount); * } * return total; * } * */public class Solution { public int hammingDistance(int x, int y) { return Integer.bitCount(x ^ y); } public int totalHammingDistance(int[] nums) { int result = 0; int j = 1; int len = nums.length; while (j<len){ for (int i=0;i<j;i++){ result += hammingDistance(nums[i],nums[j]); } j++; } return result; }}
阅读全文
0 0
- 【12月19日】LeetCode刷题日志(二):Hamming Distance
- 【12月20日】LeetCode刷题日志(四):Min Cost Climbing Stairs
- 【12月22日】LeetCode刷题日志(五):Min Cost Climbing Stairs
- 【12月22日】LeetCode刷题日志(六):132 Pattern
- 【12月19日】LeetCode刷题日志(三):Best Time to Buy and Sell Stock with Transaction Fee
- 刷题的日常[Leetcode]——461)Hamming Distance and 476)Number complement
- LeetCode | 461. Hamming Distance 12_16
- leetcode(461) Hamming Distance 简单题
- 【LeetCode】461. Hamming Distance (java实现)
- LeetCode 416 Hamming Distance(位运算)
- leetcode 461. Hamming Distance(C语言)
- LeetCode 461. Hamming Distance
- 【Leetcode】461. Hamming Distance
- [LeetCode-461]Hamming Distance
- LeetCode 461. Hamming Distance
- [LeetCode]Hamming Distance
- Leetcode 461 Hamming Distance
- LeetCode - 461. Hamming Distance
- get请求传参的最大长度
- 1.笔记本win7 centOS双系统实录
- 随记
- eclipse常见问题汇总
- 小程序:你知道的与你不知道的
- 【12月19日】LeetCode刷题日志(二):Hamming Distance
- linux 中 ~/. 是什么意思
- jsp 转long 为date 并且格式化显示
- STM32L152之RCC时钟
- 面向切面日志记录
- Html5调起安卓APP
- 分析诊断工具之三:使用show profiles分析SQL性能
- 数据结构总结之并查集
- android开发常用的缓存策略详解(2)- 先进先出(FIFO)置换算法