当前位置:网站首页>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;}};
边栏推荐
猜你喜欢
随机推荐
Anaconda virtual environment migration
leetcode 448. Find All Numbers Disappeared in an Array 找到所有数组中消失的数字(简单)
JS 内置构造函数 扩展 prototype 继承 借用构造函数 组合式 原型式creat 寄生式 寄生组合式 call apply instanceof
若依集成easyexcel实现excel表格增强
不知道这4种缓存模式,敢说懂缓存吗?
染料修饰核酸RNA|[email protected] 610/[email protected] 594/Alexa 56
Detailed AST abstract syntax tree
李沐动手学深度学习V2-自然语言推断与数据集SNLI和代码实现
「学习笔记」高斯消元
Statistical machine learning 】 【 linear regression model
那些年我写过的语言
2022 年值得尝试的 7 个 MQTT 客户端工具
【飞控开发高级教程6】疯壳·开源编队无人机-AI语音控制
自定义form表单验证
李沐动手学深度学习V2-BERT微调和代码实现
Leetcode sword refers to Offer 15. 1 in the binary number
揭秘5名运维如何轻松管理数亿级流量系统
【飞控开发高级教程3】疯壳·开源编队无人机-定高、定点、悬停
List类的超详细解析!(超2w+字)
机器学习中专业术语的个人理解与总结(纯小白)