当前位置:网站首页>每日一题:数组中数字出现的次数2
每日一题:数组中数字出现的次数2
2022-06-28 23:57:00 【利刃Cc】

链接: 数组中数字出现的次数2
这道题是前一次博客的另一个版本,想看上一个的链接在下面:
链接: 数组中数字出现的次数1
这道题与上道题不太一样的是这里出现的次数是3次还有1次的,所以异或的方法不太好整,我们可以另找方法。
我们想,既然这个数组里面只有一个数字是出现一次,其他是三次,那用一个数组把这些出现三次的数字,把他们每个二进制位统计并相加,会发现这个统计的数组中的每个位的数字都会是3的倍数,那如果又多了一个出现一次的数,那他某个二进制位上统计完加上去,会让这个数组里面某个位的数字变成模3余1,那么就可以找出这个数字为1的进制位,最后再用二进制的运算求出这个数字。总的来说:
统计出数组中的所有的数,从第1位到第32位进制位有多少个1,然后找到数组中模3余1的位数,就是这个出现一次的数字的二进制位为1的位数。
int singleNumber(int* nums, int numsSize){
//首先先统计,所以先开辟个数组
int arr[32] = {
0};
for(int i = 0; i < numsSize; i++)
{
for(int j = 0; j < 32; j++)
{
if(((nums[i]>>j) & 1) == 1)
{
arr[j] += 1;
}
}
}
//看看哪一位是出现一次的
int n = 0;
for(int i = 0; i < 32; i++)
{
if((arr[i] % 3) == 1)
{
//判断一下是不是第0位为1的情况
if(i == 0)
{
n += 1;
}
else
{
n += pow(2, i);
}
}
}
return n;
}

边栏推荐
- 小白创业做电商,选对商城系统很重要!
- 随笔记:重新认识 else if
- [buuctf.reverse] 131-135
- Solve the problem of Chinese parsing by configparser
- 转载:VTK笔记-裁剪分割-不规则闭合圈选裁剪-vtkSelectPolyData类(黑山老妖)
- Yyds dry goods count 【 vs code work record III 】 set vs code format
- 力扣(LeetCode)178. 分数排名(2022.06.27)
- The second session of question swiping and clock out activity -- solving the switching problem with recursion as the background (III)
- Auto encoder
- Typescript -- Section 5: classes
猜你喜欢

Trois questions PWN

Stm32f407------- general timer

Quartz explanation and use

Xiaobai's e-commerce business is very important to choose the right mall system!

stm32F407-------外部中断

What pitfalls should be avoided in the job interview for the operation post in 2022?

Typescript-- section 4: Functions
![[Electronic Experiment 2] simple electronic doorbell](/img/40/227f9ac1f427c1435e0e3aa02640b1.png)
[Electronic Experiment 2] simple electronic doorbell

随笔记:插入排序 --from wcc

Be on the list again! Know that Chuangyu was selected as one of the top 50 competitive enterprises in China's network security industry in 2022
随机推荐
随笔记:定义setter和getter的三种方式
Stm32f407 ------ running lamp and buzzer
Implementation of dynamic timer for quartz
What are the virtual machine software? What are their respective roles?
What are some tips to improve your interview success rate?
ERROR 1067 (42000): Invalid default value for ‘end_ time‘ Mysql
Is it safe to open an account for buying stocks online?
随笔记:模拟类数组(array-like)的方法
Typescript-- section 4: Functions
How many locks are added to an update statement? Take you to understand the underlying principles
stm32F407-------外部中断
Common mistakes in software testing
随笔记:插入排序 --from wcc
Stm32f407 ------- IO pin multiplexing mapping
Software testing tools: complete and precise
TypeScript --第三节:接口
Scrapy uses xlwt to implement the exporter that exports data in Excel format
TypeScript -- 第一节:基础类型
Stm32f407 ------- GPIO input experiment
What will be done after digital IC Verification?