当前位置:网站首页>只出现一次的数字(水了个简单题)
只出现一次的数字(水了个简单题)
2022-06-28 14:09:00 【华为云】
title: 只出现一次的数字(水了个简单题)
date: 2022-05-04 19:59:40
tags: 每天进步一点点系列
题目
题目:只出现一次的数字
给定一个非空整数数组,除了某个元素只出现一次以外,其余每个元素均出现两次。找出那个只出现了一次的元素。
说明:你的算法应该具有线性时间复杂度。 你可以不使用额外空间来实现吗?
示例 1:
输入: [2,2,1]输出: 1示例 2:
输入: [4,1,2,1,2]输出: 4题解:
本题可以直接使用异或(^,相同为0,不同为1)去解决,先说方案,异或数组中的所有数,最后剩下的就是只出现一次的数
分析:
a^a = 0 0^b = b ,所以 a^a ^ b = b
拿个数举例子:
3 ^ 3 = 0011^0011 = 0000 = 0
0 ^ 2 = 0000^0010 = 0010 = 2
所以 3^3 ^2 = 2
最后所有出现偶数次的数异或后都成0了,0在和出现一次的(其实出现奇数次也是一样)异或,得到的就是我们要的那个数了
代码:
class Solution { public int singleNumber(int[] nums) { //用异或 ,因为 a^b^a = b int res = 0; for (int num : nums) { //所以 res ^= num; } return res; }}以上就是只出现一次的数字【LeetCode】的全部内容
版权声明:
原创博主:牛哄哄的柯南
个人博客链接:https://www.keafmd.top/**
看完如果对你有帮助,感谢点击下面的==一键三连==支持!
[哈哈][抱拳]

加油!
共同努力!
Keafmd
都看到这里了,下面的内容你懂得,让我们共同进步!
边栏推荐
- 2022金属非金属矿山(地下矿山)主要负责人考试模拟100题模拟考试平台操作
- Kubernetes 深入理解kubernetes(一)
- Double buffer drawing
- Yii2 writing the websocket service of swoole
- 线程终止的 4 种方式
- Npoi export excel and download to client
- Nature子刊 | 绘制植物叶际菌群互作图谱以建立基因型表型关系
- 【二叉树】在二叉树中分配硬币
- Hematemesis recommends 17 "wheels" to improve development efficiency
- 2022下半年软考考试时间安排已确定!
猜你喜欢

Make an ink screen electronic clock, cool!

If a programmer goes to prison, will he be assigned to write code?

ArrayList源码解析

China Radio and television 5g package is coming, lower than the three major operators, but not as low as expected

Special test for cold and hot start of app

基于asp.net的文献检索系统

BERT为何无法彻底干掉BM25??

欧拉恒等式:数学史上的真正完美公式!

【中移芯昇】5. spi接口测试tf卡

Foreign trade SEO Webmaster Tools
随机推荐
Analysis and processing of GPS data format [easy to understand]
NPOI导出Excel并下载到客户端
VPS是干嘛用的?有哪些知名牌子?与云服务器有什么区别?
力扣解法汇总522-最长特殊序列 II
Yii2 connects to websocket service to realize that the server actively pushes messages to the client
Solving Hanoi Tower problem
Rslo: self supervised lidar odometer (real time + high precision, icra2022)
腾讯云国际云服务器登录之后没有网络,如何排查?
Template_ Large integer multiplication
En parlant d'exception - que se passe - t - il lorsque l'exception est lancée?
How to open an account of Huatai Securities? How to handle the account opening is the safest
What is generics and how to use generics analysis
原生JS 实现页面元素的拖动 拖拽
2022金属非金属矿山安全检查(地下矿山)复训题库及在线模拟考试
A queue of two stacks
黑苹果安装教程OC引导「建议收藏」
Simple understanding of ThreadLocal
The company leader said that if the personal code exceeds 10 bugs, he will be dismissed. What is the experience?
Build a learning environment
RAM ROM FLASH的区别