当前位置:网站首页>LeetCode 0136. 只出现一次的数字:异或
LeetCode 0136. 只出现一次的数字:异或
2022-07-25 23:31:00 【Tisfy】
【LetMeFly】136.只出现一次的数字:异或
力扣题目链接:https://leetcode.cn/problems/single-number/
给定一个非空整数数组,除了某个元素只出现一次以外,其余每个元素均出现两次。找出那个只出现了一次的元素。
说明:
你的算法应该具有线性时间复杂度。 你可以不使用额外空间来实现吗?
示例 1:
输入: [2,2,1] 输出: 1
示例 2:
输入: [4,1,2,1,2] 输出: 4
方法一:异或
异或的重要性质:
- a ⊕ b ⊕ b = a a\oplus b\oplus b=a a⊕b⊕b=a
- 0 ⊕ a = a 0\oplus a = a 0⊕a=a
- 异或结果与异或顺序无关
因此,我们用 0 0 0开始,异或每一个数,最终结果就是答案。
(除了答案都出现了两次, 0 0 0异或一个数两次还是 0 0 0;答案只出现了一次, 0 0 0异或答案一次就等于答案)
- 时间复杂度 O ( n ) O(n) O(n),其中 n n n是元素个数
- 空间复杂度 O ( 1 ) O(1) O(1)
AC代码
C++
class Solution {
public:
int singleNumber(vector<int>& nums) {
int ans = 0;
for (int& t : nums) {
ans ^= t;
}
return ans;
}
};
同步发文于CSDN,原创不易,转载请附上原文链接哦~
Tisfy:https://letmefly.blog.csdn.net/article/details/125978508
边栏推荐
- Classes and objects (3)
- 策略模式_
- Learning exploration-3d rotation card
- Grain Academy p98 trample pit e.globalexceptionhandler: null
- Bind class style and bind style style
- 新手哪个券商开户最好 开户最安全
- BI 系统中为什么会有很多快照表?
- Docker installation redis-5.0.12 (remote access)
- Which securities firm is the best and safest for beginners to open an account
- 生成随机数random学习之uniform_int_distribution,uniform_real_distribution
猜你喜欢

【JUC】并发需要了解的关键字volatile

Grain Academy p98 trample pit e.globalexceptionhandler: null

Source code of wechat applet for discerning flowers and plants / source code of wechat applet for discerning plants

@Import

意向不到的Dubug妙招

数组中重复的数字

The new UI people help task help PHP source code with a value of 1500 / reward task Tiktok Kwai headline like source code / with three-level distribution can be packaged applet

Solution of phpstudy service environment 80 port occupied by process system under Windows

Tencent map API request source is not authorized, this request source domain name

Very simple vsplayaudio online music player plug-in
随机推荐
The VM session was closed before any attempt to power it on
Apple CMS V10 template /mxone Pro adaptive film and television website template
TS interface
Duplicate numbers in array
Summary of kotlin common knowledge points
Simulate and implement common interfaces of string class
Three board axe! Help you become an excellent software engineer
学习探索-3d轮播卡片
@Import
Data broker understanding
Ffmpeg first learning (only for coding)
Family relationship calculator wechat applet source code
Tencent map API request source is not authorized, this request source domain name
@Import
S4/HANA ME21N创建PO 输出控制消息按钮丢失解决方法(切换EDI 输出模式BRF+至NAST模式)
SAP Message No. VG202 IDoc E1EDK18 中付款条款已经转移:检查数据
Source code of wechat applet for discerning flowers and plants / source code of wechat applet for discerning plants
npm+模块加载机制
Recommended system - an embedded learning framework for numerical features in CTR prediction
加拿大EE通道