当前位置:网站首页>LeetCode: 137. 只出现一次的数字 II
LeetCode: 137. 只出现一次的数字 II
2022-06-24 08:08:00 【Whisper_yl】
给你一个整数数组 nums ,除某个元素仅出现 一次外,其余每个元素都恰出现三次 。请你找出并返回那个只出现了一次的元素。
示例 1:
输入:nums = [2,2,3,2]
输出:3
示例 2:
输入:nums = [0,1,0,1,0,1,99]
输出:99
提示:
1 <= nums.length <= 3 * 104
-231 <= nums[i] <= 231 - 1
nums 中,除某个元素仅出现 一次 外,其余每个元素都恰出现 三次
分析:
基础题目为该题:136.只出现一次的数字。基础版采用了一个简单的位运算——异或运算。对于多个0和1,它们异或运算的计算,只与0和1的个数有关,与顺序无关。简而言之也就是符合交换律。所以我们只需要对这n个数各位进行异或运算即可。
而升级版不一样的地方在于只有一个数字出现了一次,其他数字都出现了三次。他们之间的区别在于,出现三次的数字,每一位,要么出现了三次0,要么出现了三次1,出现次数都是三的倍数。于是想到了统计每一位出现的次数,如果不是三的倍数,说明该位属于只出现一次的数字。依据这个思路可以解决该问题,本题重点是对位运算的操作。需要积累一下。
class Solution {
public:
int singleNumber(vector<int>& nums) {
int ans = 0;
for(int i = 0; i < 32; i++){
int total = 0;
for(int num : nums)
total += num >> i & 1; //与1相与,可得第i位结果
if(total % 3 != 0)
ans = ans | (1 << i); //第i位置为1
}
return ans;
}
};
边栏推荐
- 2020 China's provinces and cities, three-level linkage data, data agencies (data from the official website of the National Bureau of Statistics)
- eBanb B1手环刷固件异常中断处理
- [bug] @jsonformat has a problem that the date is less than one day when it is used
- L01_一条SQL查询语句是如何执行的?
- Numpy NP in numpy c_ And np r_ Explain in detail
- Support vector machine (SVC, nusvc, linearsvc)
- RISC-V架构下 FPU Context 的动态保存和恢复
- 【LeetCode】387. First unique character in string
- 每周推薦短視頻:談論“元宇宙”要有嚴肅認真的態度
- leetcode--字符串
猜你喜欢

EasyExcel单sheet页与多sheet页写出

Solution: the word of jmeter5.5 on the win11 lower interface is very small

从618看京东即时零售的野心

I heard that you are still spending money to buy ppt templates from the Internet?

2022.06.23 (traversal of lc_144,94145\
![[noi Simulation Competition] send (tree DP)](/img/5b/3beb9f5fdad00b6d5dc789e88c6e98.png)
[noi Simulation Competition] send (tree DP)

Webrtc series - network transmission 5: select the optimal connection switching

ApplicationContextInitializer的三种使用方法

零基础自学SQL课程 | 子查询
Depens:*** but it is not going to be installed
随机推荐
Zero foundation self-study SQL course | syntax sequence and execution sequence of SQL statements
Yolox backbone -- implementation of cspparknet
The native applet uses canvas to make posters, which are scaled to the same scale. It is similar to the uniapp, but the writing method is a little different
Thinkphp5清除runtime下的cache缓存,temp缓存,log缓存
Common emoticons
【Redis实现秒杀业务①】秒杀流程概述|基本业务实现
php单例模式详解
PM2 deploy nuxt3 JS project
正则匹配手机号
普通人没有学历,自学编程可以月入过万吗?
Numpy numpy中的np.c_和np.r_详解
Software system dependency analysis
What do you mean by waiting for insurance records? Where should I go for filing?
Leetcode -- wrong set
【Redis實現秒殺業務①】秒殺流程概述|基本業務實現
PhpStrom代码格式化设置
正则匹配邮箱
【LeetCode】387. First unique character in string
LeetCode之最长公共前缀
每周推荐短视频:计算的终极形态是“元宇宙”?