当前位置:网站首页>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 007. 数组中和为 0 的三个数(双指针)
- 调用EasyCVR接口时视频流请求出现404,并报错SSL Error,是什么原因?
- 化算力为战力:宁夏中卫的数字化转型启示录
- leetcode 268. 丢失的数字(异或!!)
- 染料修饰核酸RNA|[email protected] 610/[email protected] 594/Alexa 56
- Why BI software can't handle correlation analysis
- MySQL Basics
- Advantages and Disadvantages of Blind and Buried Via PCB Stacked Via Design
- leetcode 1837. The sum of the digits in the K-base representation
猜你喜欢

Advantages and Disadvantages of Blind and Buried Via PCB Stacked Via Design

Anaconda 虚拟环境迁移

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

数学之美 第六章——信息的度量和作用

ESP8266-Arduino编程实例-WS2812驱动

从腾讯阿里等大厂出来创业搞 Web3、元宇宙的人在搞什么

RNA-ATTO 390|RNA-ATTO 425|RNA-ATTO 465|RNA-ATTO 488|RNA-ATTO 495|RNA-ATTO 520近红外荧光染料标记核糖核酸RNA

安装anaconda并创建虚拟环境

EMQX Newsletter 2022-07|EMQX 5.0 正式发布、EMQX Cloud 新增 2 个数据库集成

双线性插值公式推导及Matlab实现
随机推荐
Golang死信队列的使用
Mapper输出数据中文乱码
JS 内置构造函数 扩展 prototype 继承 借用构造函数 组合式 原型式creat 寄生式 寄生组合式 call apply instanceof
模板字符串概述
leetcode 2119. Numbers reversed twice
力扣206-反转链表——链表
ESP8266-Arduino编程实例-BH1750FVI环境光传感器驱动
ES6-箭头函数
leetcode 072. Finding Square Roots
汉源高科8光口12电口交换机千兆8光8电12电16电网管型工业以太网交换机
那些年我写过的语言
嵌入式分享合集27
力扣59-螺旋矩阵 II——边界判断
软件测试基本流程有哪些?权威的第三方软件检测机构推荐
leetcode 16. 数值的整数次方(快速幂+递归/迭代)
NNLM、RNNLM等语言模型 实现 下一单词预测(next-word prediction)
JWT详解
盲埋孔PCB叠孔设计的利与弊
tRNA-m5C转运RNA(tRNA)修饰5-甲基胞嘧啶(m5C)|tRNA修饰m1Am2A (2-methyladenosine)
leetcode 125. 验证回文串