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

边栏推荐
- Unity—“合成大西瓜”小游戏笔记
- Black cat takes you to learn EMMC Protocol Part 26: hardware reset operation of EMMC (h/w reset)
- With 433 remote control UV lamp touch chip-dlt8sa20a-jericho
- Low code: reduce technical capability requirements and improve software development efficiency
- Led aquarium lamp touch chip-dlt8t02s-jericho
- MySQL 实践篇 —— 主从复制
- 【嵌入式C基础】第9篇:C语言指针的基本用法
- Ruan Bonan of Green Alliance Technology: cloud native security from the open source shooting range
- 为什么说Crypto游戏正在改变游戏产业?
- [FPGA]: ise and Modelsim joint simulation
猜你喜欢

Led aquarium lamp touch chip-dlt8t02s-jericho

Bull spread portfolio

我抄底了被清算的NFT,却被OpenSea上了锁

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

Installation and reinstallation of win11 system graphic version tutorial

With 433 remote control UV lamp touch chip-dlt8sa20a-jericho

拥有游戏的一部分,写在我的世界禁用NFT之后

2020-12-07

One track education, PHP training, unity of knowledge and practice, popular

Call / put option price curve
随机推荐
[embedded C foundation] Part 8: explanation of C language array
The form select in antd is received before it is selected
企业数字化本质
.net for subtraction, intersection and union of complex type sets
Storage model: big end and small end
Table list filter results remain unchanged
Li FuPan: application practice of kata safety container in ant group
Code layered management of interface testing based on RF framework
[embedded explanation] key scanning based on finite state machine and stm32
STM32 Development Notes - experience sharing
Machine learning Basics - decision tree-12
Understanding of vite2
Complete set of SSM framework online bookstore
With 433 remote control UV lamp touch chip-dlt8sa20a-jericho
Resolve browser password echo
10、 Kubernetes scheduling principle
【嵌入式C基础】第2篇:进制转换与BCD编码
面试必问,敲重点!讲一下 Android Application 启动流程及其源码?
Phpstudy steps to quickly build a website (teach you to build it by hand)
【嵌入式C基础】第3篇:常量和变量