当前位置:网站首页>leetcode 136. Numbers that appear only once (XOR!!)
leetcode 136. Numbers that appear only once (XOR!!)
2022-08-03 20:13:00 【Luna who can program】
Given a non-empty array of integers, each element appears twice except one that appears only once.Find the element that appears only once.
Description:
Your algorithm should have linear time complexity.Can you do it without using extra space?
Example 1:
Input: [2,2,1]
Output: 1
Example 2:
Input: [4,1,2,1,2]
Output: 4
Ideas: Use XOR
The XOR operation has the following three properties:
- If any number is XORed with 0, the result is still the original number, i.e. a^0=a .
- Any number is XORed with itself, the result is 0, that is, a^a=0.
- The XOR operation satisfies the commutative and associative laws, that is, a ^ b ^ a=b ^ a ^ a=b ^ (a ^ a)=b ^ 0=b .
At the beginning, let int ans=0, traverse the entire array and perform an XOR operation. Since the elements that appear 2 times are XORed 2 times, they are still themselves, and finally only the elements that have XORed 1 times are left, and because 0XOR with any number is that number itself, so in the end only one occurrence of the number is left.
class Solution {public:int singleNumber(vector<int>& nums) {int ans=0;int n=nums.size();for(int i=0;i<n;++i)ans^=nums[i];return ans;}};边栏推荐
猜你喜欢
随机推荐
EMQX Newsletter 2022-07|EMQX 5.0 正式发布、EMQX Cloud 新增 2 个数据库集成
Advantages and Disadvantages of Blind and Buried Via PCB Stacked Via Design
染料修饰核酸RNA|[email protected] 610/[email protected] 594/Alexa 56
leetcode 326. Powers of 3
EasyCVR平台海康摄像头语音对讲功能配置的3个注意事项
NNLM、RNNLM等语言模型 实现 下一单词预测(next-word prediction)
MySQL Basics
ARMuseum
软件测试基本流程有哪些?权威的第三方软件检测机构推荐
YARN功能介绍、交互流程及调度策略
第三方验收测试报告有什么作用?如何获取权威软件测试报告?
【飞控开发高级教程6】疯壳·开源编队无人机-AI语音控制
tRNA甲基化偶联3-甲基胞嘧啶(m3C)|tRNA-m3C (3-methylcy- tidine)
Hinton2022年RobotBrains访谈记录
Auto.js实现朋友圈自动点赞
【飞控开发高级教程4】疯壳·开源编队无人机-360 度翻滚
ESP8266-Arduino编程实例-MCP4725数模转换器驱动
Why BI software can't handle correlation analysis
李沐动手学深度学习V2-BERT微调和代码实现
node版本切换工具NVM以及npm源管理器nrm









