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

【leetcode】剑指 Offer II 009. 乘积小于 K 的子数组(滑动窗口、双指针)

信使mRNA甲基化偶联3-甲基胞嘧啶(m3C)|mRNA-m3C

为什么 BI 软件都搞不定关联分析

Detailed demonstration pytorch framework implementations old photo repair (GPU)

NNLM、RNNLM等语言模型 实现 下一单词预测(next-word prediction)

Edge box + time series database, technology selection behind Midea's digital platform iBuilding

CLIP论文解读

双线性插值公式推导及Matlab实现

机器学习中专业术语的个人理解与总结(纯小白)

node版本切换工具NVM以及npm源管理器nrm
随机推荐
Anaconda 虚拟环境迁移
8.3模拟赛总结
leetcode 16. 数值的整数次方(快速幂+递归/迭代)
Anaconda virtual environment migration
In-depth understanding of JVM-memory structure
边缘盒子+时序数据库,美的数字化平台 iBuilding 背后的技术选型
tensorflow-gpu2.4.1安装配置详细步骤
622 设计循环队列——Leetcode天天刷【循环队列,数组模拟,双指针】(2022.8.2)
2022.8.2
CLIP论文解读
Go语言为任意类型添加方法
abs()、fabs() 和 labs() 的区别
涨薪5K必学高并发核心编程,限流原理与实战,分布式计数器限流
leetcode 1837. K 进制表示下的各位数字总和
极验深知v2分析
若依集成browscap读取浏览器用户代理
亚马逊云科技 Build On 2022 - AIot 第二季物联网专场实验心得
149. The largest number on a straight line, and check the set
async 和 await 原来这么简单
友宏医疗与Actxa签署Pre-M Diabetes TM 战略合作协议