当前位置:网站首页>LeetCode136:只出现一次的数字
LeetCode136:只出现一次的数字
2022-08-03 14:05:00 【Hugh.L】
题目
给定一个非空整数数组,除了某个元素只出现一次以外,其余每个元素均出现两次。找出那个只出现了一次的元素。
说明:
你的算法应该具有线性时间复杂度。 你可以不使用额外空间来实现吗?
示例 1:
输入: [2,2,1]
输出: 1
示例 2:
输入: [4,1,2,1,2]
输出: 4
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/single-number
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
分析
这是《数据结构基础》中的第一道题,主要思想是位运算中异或运算,可参考以下:
任何数于0异或为任何数 0 ^ n => n
相同的数异或为0: n ^ n => 0
例如:2 ^ 3 ^ 2 ^ 4 ^ 4等价于 2 ^ 2 ^ 4 ^ 4 ^ 3 => 0 ^ 0 ^3 => 3
故对于本题,想找到只出现一次的元素,只需要将数组中的每个数进行异或运算,出现两次的数异或为0(n ^ n => 0),最后只剩下只出现一次的数(0 ^ n => n)。
实现
本题,个人采用C++实现,原理弄清楚后,还需要了解异或函数【bit_xor()】的使用。具体使用示例整理如下:
#include <algorithm>
#include <functional> // to include bit_xor
#include <iostream>
#include <iterator>
using namespace std;
int main()
{
// declaring the values
int A[] = { 1, 2, 3, 4, 5, 6 };
int B[] = { 6, 7, 8, 4, 5, 0 };
int n = 6;
// defining result
int result[n];
// transform is used to apply bitwise_xor
// on the arguments A and B
transform(A, end(A), B,
result, bit_xor<int>());
// printing the resulting array
cout << "A xor B = ";
for (const int& answer:result)
cout << ' ' << answer;
return 0;
}
上述例子是对于两个数组进行异或,事实上,针对本题对一个数组中所有数进行异或,可以写成
accumulate(nums.begin(),nums.end(),0,bit_xor());
综上,可以得出以下代码:
class Solution {
public:
int singleNumber(vector<int>& nums) {
int a=0;
for(int i=0;i<sizeof(nums);i++)
{
a=accumulate(nums.begin(),nums.end(),0,bit_xor());
}
return a;
}
};
边栏推荐
- Ansible中的角色使用
- Nanoprobes FluoroNanogold 偶联物的特色和应用
- ideaIU-2020.1下载
- PCL 点云按时间进行分段
- 软件测试考证:ISTQB、软件评测师
- 爬虫——代理搭建、爬取视频网站、爬取新闻、BeautifulSoup4介绍、bs4 遍历文档树、bs4搜索文档树、bs4使用选择器
- HCIP Fifteenth Day Notes (Three-layer Architecture of Enterprise Network, VLAN and VLAN Configuration)
- 半导体制造业回流美国?宏碁创始人施振荣:违反垂直分工大趋势
- 162_Power Query is a custom function for quickly merging tables in a folder TableXlsxCsv_2.0
- atrace和systrace的基本使用方法
猜你喜欢
随机推荐
GMapping原理分析[通俗易懂]
System learning Shell regular expressions
金立前高管团队再战手机市场,创立新品牌“FreeYond”
连亏四个月,赚不回电费,预制菜经销商恐成“韭菜”?
基于ModelArts的动漫头像自动生成丨【华为云至简致远】
如何使用matlab实现分段函数「建议收藏」
ideaIU-2020.1下载
硬件业务收入下滑,为了赚钱,苹果暧昧对待流氓软件和增加广告了
ITSM软件与工单系统的区别是什么?
想成为网络安全技术爱好者(可能是黑客)的话,需要看什么书?
为什么手动启动GBase 8c数据库中GTM节点
Zhang Le: The Golden Triangle of R&D Efficiency and Practice in the Field of Demand and Agile Collaboration|Live Review
致一位湖南女孩
【二叉树】统计最高分的节点数目
162_Power Query is a custom function for quickly merging tables in a folder TableXlsxCsv_2.0
secureCRT连接开发板连接不上问题解决
【二叉树】从二叉树一个节点到另一个节点每一步的方向
CVPR 2022 | Predicting Skeletons from Human Meshes, True Physiological Skeletons!
【框架】idea找不到xxx依赖项怎么办
【深度学习中的激活函数的整理与使用总结】