当前位置:网站首页>leetcode-136.只出现一次的数字
leetcode-136.只出现一次的数字
2022-07-28 12:08:00 【KGundam】
位运算
题目详情
给定一个非空整数数组,除了某个元素只出现一次以外,其余每个元素均出现两次。找出那个只出现了一次的元素。
说明:
你的算法应该具有线性时间复杂度。 你可以不使用额外空间来实现吗?
示例1:
输入: [2,2,1]
输出: 1
示例2:
输入: [4,1,2,1,2]
输出: 4
思路:
我们可以利用 x ∧ x = 0 和 x ∧ 0 = x 的特点,将数组内所有的数字进行按位异或。出现两次
的所有数字按位异或的结果是 0,0 与出现一次的数字异或可以得到这个数字本身。
数组中的相同元素并不是挨着的,那么异或还能实现两两抵消嘛?
不要怕,异或运算是满足交换律的! a ^ b ^ c <=> a ^ c ^ b
我的代码:
class Solution
{
public:
int singleNumber(vector<int>& nums)
{
int ans = 0;
for (const int & num : nums)
{
ans ^= num;
}
return ans;
}
};
位运算常用技巧

边栏推荐
- Fundamentals of machine learning - principal component analysis pca-16
- The difference between sessionstorage, localstorage and cookies
- [embedded C foundation] Part 7: detailed introduction to C language process control
- .net for subtraction, intersection and union of complex type sets
- 黑猫带你学eMMC协议第24篇:eMMC的总线测试程序详解(CMD19 & CMD14)
- [matlab] IIR filter
- 9、 Kubernetes configuration and storage
- Pointnet++ Chinese Translation
- 为什么说Crypto游戏正在改变游戏产业?
- Dimming and color matching cool light touch chip-dlt8ma12ts-jericho
猜你喜欢

Low code: reduce technical capability requirements and improve software development efficiency

LeetCode每日一题(2196. Create Binary Tree From Descriptions)

一根筋教育PHP培训 知行合一收热捧

【嵌入式C基础】第5篇:原码/反码/补码
![[graduation design] smart home system based on ZigBee - single chip microcomputer Internet of things stm32](/img/c3/4268d7e4e1429f9b0d9d928790d740.png)
[graduation design] smart home system based on ZigBee - single chip microcomputer Internet of things stm32

butterfly spreads

Black cat takes you to learn EMMC Protocol Part 26: hardware reset operation of EMMC (h/w reset)

Remove the plug-in of category in WordPress link

Black cat takes you to learn EMMC Protocol Part 24: detailed explanation of EMMC bus test program (cmd19 & cmd14)

Unity—“合成大西瓜”小游戏笔记
随机推荐
One track education, PHP training, unity of knowledge and practice, popular
【嵌入式C基础】第1篇:基本数据类型
Form for real-time custom verification
What if win11 cannot recognize Ethernet
Databinding+LiveData轻松实现无重启换肤
Chinese translation of pointnet:deep learning on point sets for 3D classification and segmentation
【嵌入式C基础】第4篇:运算符的使用
[FPGA]: Joint Simulation of FPGA and MATLAB
[embedded C foundation] Part 2: binary conversion and BCD coding
Installation and reinstallation of win11 system graphic version tutorial
【嵌入式C基础】第8篇:C语言数组讲解
机器学习基础-决策树-12
[embedded C foundation] Part 1: basic data types
[embedded C foundation] Part 4: use of operators
SSM框架网上书城全套
[FPGA] FIR filter - half band filter
Bear market spread portfolio
Redis —— 基础篇
Aragon创建DAO polygon BSC测试网
Ruan Bonan of Green Alliance Technology: cloud native security from the open source shooting range