当前位置:网站首页>477. 汉明距离总和
477. 汉明距离总和
2022-07-20 22:24:00 【baixiaofei567】
一开始暴力了,想想就不行,立方级别的时间复杂度肯定不行的。
不用两两异或,通过统计这个数组中每一位的1的个数和0的个数即可。因为是有范围不大于10^9也就是2 ^30,所以我们只要遍历0到30位就行,用每一位上的1的个数和0的个数相乘,就是这一位上能提供的所有汉明距离的和。
1就是(val>>i)&1,0的个数就是n-c。为什么是0和1的相乘,就相当于做一个组合运算,用这一位是1的数字和另一个这一位是0的数字异或才能提供11的汉明距离,所以只要0的个数1的个数就是这一位所能提供的汉明距离和。
class Solution {
public:
int totalHammingDistance(vector<int>& nums) {
// int res = 0;
// int a = 0;
// for(int i = 0; i < nums.size(); ++i){
// for(int j = i + 1; j < nums.size(); ++j){
// a = nums[i] ^ nums[j];
// while(a != 0){
// a &= (a-1);
// res++;
// }
// }
// }
// return res;
//不用两两异或,通过统计这个数组中每一位的1的个数和0的个数即可
//
int res = 0, n = nums.size();
for(int i = 0; i < 30; ++i){
int c = 0;
for(int val : nums){
c += (val >> i) & 1;
}
res += c * (n-c);
}
return res;
}
};
边栏推荐
- [Baoyan] - oral English skills in Baoyan summer camp
- (pc+wap) Zhimeng template starch website
- 初识无影云电脑
- Pit encountered by pl/sql
- Jz25 merge two sorted linked lists
- 调佣金需要去证券公司营业部吗,手机上开户安不安全
- 100页幻灯片图解《数据出境安全评估办法》及修订对照(附下载)
- Ça marche! Jira + Zadig Implementation Requirements and R & D Process Tracking
- 中国邮储银行 IT 集采:服务器、阵列、交换机、路由器、防火墙等
- [leetcode] use bisection in unordered arrays
猜你喜欢
View的滑动
Ython + selenium web automation 2022 updated tutorial automated testing software test crawler - Notes blog collation
ABAP语法基础
前 3 名突然变了,揭秘 7 月编程语言最新排行榜
ython + Selenium Web自动化 2022更新版教程 自动化测试 软件测试 爬虫-笔记博客整理
STM32串口屏学习
消息队列-rockerMQ开发实战
RKE vs. rke2: compare two kubernetes distributions
Fiddler设置断点
Yuntu says digital asset chain: your God of digital asset property protection
随机推荐
【保研】-- 保研夏令营中线上面试注意事项
我来告诉你,一个草根程序员如何逆袭,成功进入BAT!
Yuntu says digital asset chain: your God of digital asset property protection
Redis内存模型讲解
Jz69 jumping steps
100 page slide illustration "data exit safety assessment measures" and revision comparison (download attached)
ython + Selenium Web自动化 2022更新版教程 自动化测试 软件测试 爬虫-笔记博客整理
LNMP------PHP7安装
[leetcode] binary search problem solution summary
【保研】-- 整理分享一下之前学校复试面试存在的问题
【FLink】Flink 任务 如何优雅的停止
Push in and pop-up sequence of jz31 stack
Ython + selenium web automation 2022 updated tutorial automated testing software test crawler - Notes blog collation
满街皆是圣贤是可能的
[guaranteed research] - sort out and share the problems existing in the previous school reexamination interview
The penultimate K nodes in jz22 linked list
OPENCV学习DAY2
JS optional chain
打通了!Jira + Zadig 实现需求与研发过程追踪
Scala exercises student scores case