博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode 477: Total Hamming Distance
阅读量:6905 次
发布时间:2019-06-27

本文共 1288 字,大约阅读时间需要 4 分钟。

Note:

1. Very smart way of calculating how many difference from bits: https://en.wikipedia.org/wiki/Hamming_distance#Algorithm_example

2. Another way is counting how many 1s and 0s per bits. Then the contribution of that bit will bt C(1, k) * C(1, n - k).

class Solution {    public int totalHammingDistance(int[] nums) {        if (nums.length < 2) {            return 0;        }                int result = 0;;        for (int i = 0; i < nums.length; i++) {            for (int j = i + 1; j < nums.length; j++) {                result += getDistance(nums[i], nums[j]);            }        }        return result;    }        private int getDistance(int a, int b) {        int c = a ^ b;        int result = 0;        while (c != 0) {            result++;            c &= c - 1;        }        return result;    }}
class Solution {    public int totalHammingDistance(int[] nums) {        if (nums.length < 2) {            return 0;        }                int result = 0;;        for (int i = 0; i < 32; i++) {            int ones = 0;            for (int j = 0; j < nums.length; j++) {                ones += (nums[j] >> i) & 1;            }            result += ones * (nums.length - ones);        }        return result;    }}

 

转载于:https://www.cnblogs.com/shuashuashua/p/7469865.html

你可能感兴趣的文章
利用HttpClient 4.1 下载文件
查看>>
LNMP环境搭建-php
查看>>
Hadoop云计算的初步认识
查看>>
windows下创建控制台窗口
查看>>
JVM配置参数
查看>>
jBPM5与Activiti5比较
查看>>
iOS App 的逆向
查看>>
Spring如何扫描class和配置文件
查看>>
Java压缩技术(一) ZLib
查看>>
【VMware虚拟化解决方案】VMware Horizon View Client 各平台配置文档
查看>>
java线程池
查看>>
Linux内核线程
查看>>
Linux cp时总询问是否覆盖,怎样让它不询问直接覆盖
查看>>
笨方法学python Lesson 45
查看>>
Java HashMap的实现原理
查看>>
服务器的发送数据
查看>>
kvm install 报错could not open disk imageXXX: Permission denied
查看>>
lduan office 365 自定义域的添加和配置二
查看>>
在Wordpress侧栏中使用下拉菜单显示分类
查看>>
基础排序算法 – 选择排序Selection sort
查看>>