当前位置:网站首页>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
边栏推荐
- Kotlin 常用知识点汇总
- [QNX hypervisor 2.2 user manual]9.6 GDB
- 电商RPA,大促轻松上阵的法宝
- WordPress removes the website publishing time
- How to set pseudo static for WordPress fixed links
- 新手哪个券商开户最好 开户最安全
- 【代码案例】博客页面设计(附完整源码)
- Multimodal deep multi modal sets
- Solution of phpstudy service environment 80 port occupied by process system under Windows
- Graph traversal DFS, BFS (code explanation)
猜你喜欢

数组中重复的数字

MVVM model

Duplicate numbers in array

E-commerce RPA, a magic weapon to promote easy entry

生成随机数random学习之uniform_int_distribution,uniform_real_distribution

initializer_list工具库学习

行云管家V6.5.1/2/3系列版本发布:数据库OpenAPI能力持续强化

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

Idea sets get and set templates to solve the naming problem of boolean type fields

npm+模块加载机制
随机推荐
2022 Niuke multi School Game 2
图的遍历-DFS,BFS(代码详解)
Docker installation redis-5.0.12 (remote access)
This point inside the function / change this point inside the function
Classes and objects (3)
Moment.js
Call Gaode map -- address is converted into longitude and latitude
WebMvcConfigurationSupport
Thinkphp6 temporarily close the layout
Source code of YY music wechat applet imitating Netease cloud music
Wrote a little webapi knowledge points from 0 to 1
【MUDUO】Thread封装
推荐系统——An Embedding Learning Framework for Numerical Features in CTR Prediction
Which securities firm is the best and safest for beginners to open an account
Deep and shallow copies
[QNX Hypervisor 2.2用户手册]9.8 load
Qt风格(QSS)应用之QProgressBar
serialization and deserialization
行云管家V6.5.1/2/3系列版本发布:数据库OpenAPI能力持续强化
Scaffold installation