当前位置:网站首页>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;}};
边栏推荐
- YARN功能介绍、交互流程及调度策略
- 李沐动手学深度学习V2-自然语言推断与数据集SNLI和代码实现
- 抖音web逆向教程
- leetcode 461. 汉明距离
- EasyCVR平台海康摄像头语音对讲功能配置的3个注意事项
- 力扣203-移除链表元素——链表
- Detailed explanation of JWT
- leetcode 268. 丢失的数字(异或!!)
- JS 内置构造函数 扩展 prototype 继承 借用构造函数 组合式 原型式creat 寄生式 寄生组合式 call apply instanceof
- 149. The largest number on a straight line, and check the set
猜你喜欢
随机推荐
揭秘5名运维如何轻松管理数亿级流量系统
LeetCode 899. 有序队列
LeetCode 622. 设计循环队列
子结点的数量(2)
染料修饰核酸RNA|[email protected] 610/[email protected] 594/Alexa 56
调用EasyCVR接口时视频流请求出现404,并报错SSL Error,是什么原因?
pytorch框架实现老照片修复功能详细演示(GPU版)
leetcode 231. 2 的幂
RNA核糖核酸修饰荧光染料|HiLyte Fluor 488/555/594/647/680/750标记RNA核糖核酸
ARMuseum
leetcode 448. Find All Numbers Disappeared in an Array 找到所有数组中消失的数字(简单)
leetcode 1837. K 进制表示下的各位数字总和
算法--交错字符串(Kotlin)
「学习笔记」高斯消元
CSDN帐号管理规范
codeforces:C. Maximum Subrectangle【前缀和 + 贪心 + 最小子数组和】
详解AST抽象语法树
leetcode 16. 数值的整数次方(快速幂+递归/迭代)
力扣707-设计链表——链表
Likou 707 - Design Linked List - Linked List