当前位置:网站首页>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;
}
};
位运算常用技巧

边栏推荐
- [FPGA]: MATLAB generates COE files
- Rust 从入门到精通01-简介
- Bull spread portfolio
- Low code: reduce technical capability requirements and improve software development efficiency
- 黑猫带你学UFS协议第2篇:UFS相关名词释义
- Jetpack Compose 完全脱离 View 系统了吗?
- Stepless dimming colorful RGB mirror light touch chip-dlt8s12a-jericho
- Dimming and color matching cool light touch chip-dlt8ma12ts-jericho
- QT signal and slot mechanism (detailed)
- Pointnet++ Chinese Translation
猜你喜欢

Risk analysis of option trading

How to improve deep learning performance?
![[graduation design] heart rate detection system based on single chip microcomputer - STM32 embedded Internet of things](/img/b4/06c822c52f5bb0045698b7107efb26.png)
[graduation design] heart rate detection system based on single chip microcomputer - STM32 embedded Internet of things

Original juice multifunctional Juicer touch chip-dlt8t02s-jericho
![[pictures and texts] detailed tutorial of one click reinstallation of win11 system](/img/cc/749fe4095fc5afb1fc2c65df43d06c.png)
[pictures and texts] detailed tutorial of one click reinstallation of win11 system

Machine learning Basics - integrated learning-13

Machine learning Basics - decision tree-12

What if the right button of win11 start menu doesn't respond

LeetCode·每日一题·1331.数组序号转换·离散化

Led aquarium lamp touch chip-dlt8t02s-jericho
随机推荐
BiliBili Yang Zhou: above efficiency, efficient delivery
Form for real-time custom verification
RGB game atmosphere light touch chip-dlt8s04a-jericho
Change password, confirm password verification antd
With 433 remote control UV lamp touch chip-dlt8sa20a-jericho
[pictures and texts] detailed tutorial of one click reinstallation of win11 system
【嵌入式C基础】第4篇:运算符的使用
CTO of youhaoda, MVP of Huawei cloud, and Zhang Shanyou: build cloud native applications based on kubernetes and dapr
Automatic light sensing arm lamp touch chip-dlt8sa15b-jericho
GameStop熊市杀入NFT交易,老牌游戏零售商借Web3焕发第二春
Qt 信号和槽机制( 详解 )
如何在 TiDB Cloud 上使用 Databricks 进行数据分析 | TiDB Cloud 使用指南
What if the right button of win11 start menu doesn't respond
黑猫带你学eMMC协议第27篇:什么是eMMC的动态容量(Dynamic Capacity)?
SQL most commonly used basic operation syntax
Unity—“合成大西瓜”小游戏笔记
Bear market spread portfolio
Machine learning practice - decision tree-22
Low code: reduce technical capability requirements and improve software development efficiency
[embedded C foundation] Part 4: use of operators