当前位置:网站首页>力扣 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;
}
边栏推荐
猜你喜欢

Shell basic concepts and variables

Leetcode-190. inverting binary bits

【黑马早报】字节估值缩水,降至2700亿美元;“二舅”视频作者回应抄袭;任泽平称取消商品房预售制是大势所趋;美联储宣布再加息75个基点...

GO语言-栈的应用-表达式求值

How to design a second kill system?

Why is crypto game changing the game industry?

微念“失去”李子柒的这一年

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

基于神经网络的帧内预测和变换核选择

屈辱、抗争、逆转,三十年,中国该赢微软一次了
随机推荐
[matlab]: FFT related problems
什么叫杂谈(e网杂谈)
Deployment之滚动更新策略。
Go language - Application of stack - expression evaluation
JS method of splitting strings
Extended operator
Dimming and color matching cool light touch chip-dlt8ma12ts-jericho
Single option trading and cross trade
Black Scholes Merton European option pricing formula
Jenkins--持续集成服务器
Margin calculation
Cesium pit -- pit used by various API calls and API itself
[FPGA]: ise and Modelsim joint simulation
Map tiles: detailed explanation of vector tiles and grid tiles
Chapter 6 提升
Call / put option price curve
Realize the mutual value transfer between main window and sub window in WPF
vim常用命令详解(vim使用教程)
RGB game atmosphere light touch chip-dlt8s04a-jericho
Aragon creates Dao polygon BSC test network