当前位置:网站首页>力扣 2354. 优质数对的数目
力扣 2354. 优质数对的数目
2022-07-28 12:20:00 【三更鬼】
题目来源:https://leetcode.cn/problems/number-of-excellent-pairs/
大致题意:
给定一个数组和整数 k,找出不重复的优质数对的数目(若[1, 2] 是优质数对,则 [2, 1] 也是优质数对,不算重复),优质数对是指:
- 设数对两个元素为 num1、num2,若 num1 & num2 和 num1 | num2 两个结果对应二进制中 1 的个数大于等于 k,则为优质数对
思路
num1 & num2 和 num1 | num2 两个结果对应二进制中 1 的个数
等价于
num1 和 num2 对应二进制中位置相同的 1 的个数 * 2 与 num1 和 num2 对应二进制中位置不同的 1 的个数
也就等价于
num1 和 num2 本身二进制中 1 的个数
所以这道题其实就是脑筋急转弯,优质数对就是两个数的二进制中 1 的个数大于等于 k
那么解题步骤为:
- 使用一个 bitCount 数组统计原数组元素二进制中不同 1 的个数的出现次数
- 双重循环枚举 1 的个数大于等于 k 的数对个数
具体看代码:
public long countExcellentPairs(int[] nums, int k) {
int n = nums.length;
long ans = 0;
// 存二进制不同 1 的个数的统计值
int[] bitCount = new int[33];
// 用来去重
Set<Integer> set = new HashSet<>();
// 统计
for (int i = 0; i < n; i++) {
// 不统计重复数字
if (set.add(nums[i])) {
bitCount[Integer.bitCount(nums[i])]++;
}
}
// 枚举优质数对个数
for (int i = 1; i < 33; i++) {
for (int j = 1; j < 33; j++) {
// 当 1 的个数大于等于 k 时,即为优质数对
if (i + j >= k) {
// 计算笛卡尔积并统计
ans += bitCount[i] * bitCount[j];
}
}
}
return ans;
}
边栏推荐
- 基于pytorch卷积人脸表情识别–毕业设计「建议收藏」
- Guide for using IP phone system and VoIP system
- Using auto.js to realize the function of fifaol3 mobile terminal card interceptor
- MySQL practice -- master-slave replication
- powerdesigner创建数据库模型(概念模型举例)
- 少儿编程 电子学会图形化编程等级考试Scratch二级真题解析(判断题)2022年6月
- 微念“失去”李子柒的这一年
- The form select in antd is received before it is selected
- Led aquarium lamp touch chip-dlt8t02s-jericho
- Leetcode-190. inverting binary bits
猜你喜欢

为什么说Crypto游戏正在改变游戏产业?

管理区解耦架构见过吗?能帮客户搞定大难题的

Change password, confirm password verification antd

Led aquarium lamp touch chip-dlt8t02s-jericho

夜神模拟器抓包微信小程序
![[matlab]: FFT related problems](/img/08/c721394c172bdfd1d5d55aef31ccbf.png)
[matlab]: FFT related problems

Rust 从入门到精通01-简介

Go language - Application of stack - expression evaluation

UV germicidal lamp chip dlt8p65sa Jericho

GameStop熊市杀入NFT交易,老牌游戏零售商借Web3焕发第二春
随机推荐
Leetcode-190. inverting binary bits
Definition of option basis
夜神模拟器抓包微信小程序
ES6 null merge operator (?)
Rust 从入门到精通01-简介
沾上趣店,都得道歉?
从手机厂高位“出走”的三个男人
Dimming and color matching cool light touch chip-dlt8ma12ts-jericho
butterfly spreads
Array, string de duplication
[FPGA]: ise and Modelsim joint simulation
屈辱、抗争、逆转,三十年,中国该赢微软一次了
How much do you know about JVM memory management
docker部署mysql 实现远程连接[通俗易懂]
什么是事务及数据库的优化方法
Guide for using IP phone system and VoIP system
Using auto.js to realize the function of fifaol3 mobile terminal card interceptor
二舅能治好年轻人的精神内耗吗?
什么叫杂谈(e网杂谈)
Sub thread update UI full solution