当前位置:网站首页>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;}};边栏推荐
猜你喜欢

Matlab paper illustration drawing template No. 42 - bubble matrix diagram (correlation coefficient matrix diagram)

Abs (), fabs () and LABS ()

演讲议题及嘉宾重磅揭晓,TDengine 开发者大会推动数据技术“破局”

codeforces:C. Maximum Subrectangle【前缀和 + 贪心 + 最小子数组和】

xss.haozi练习通关详解

简易电子琴设计(c语言)

CLIP论文解读

涨薪5K必学高并发核心编程,限流原理与实战,分布式计数器限流

Anaconda 虚拟环境迁移

那些年我写过的语言
随机推荐
Detailed steps for tensorflow-gpu2.4.1 installation and configuration
8.3模拟赛总结
tensorflow-gpu2.4.1安装配置详细步骤
涨薪5K必学高并发核心编程,限流原理与实战,分布式计数器限流
C中的数据存储
盲埋孔PCB叠孔设计的利与弊
【STM32】标准库-自定义BootLoader
调用EasyCVR接口时视频流请求出现404,并报错SSL Error,是什么原因?
charles配置客户端请求全部不走缓存
leetcode 2119. 反转两次的数字
Auto.js脚本程序打包
子结点的数量(2)
Statistical machine learning 】 【 linear regression model
WPF .cs中使用资源文件中的ControlTemplate或Style并找到控件
Why BI software can't handle correlation analysis
ES6解构赋值--数组解构及对象解构
倒计时2天,“文化数字化战略新型基础设施暨文化艺术链生态建设发布会”启幕在即
为什么 BI 软件都搞不定关联分析
【微信小程序2】事件传参与数据同步[03]
async 和 await 原来这么简单